I have the following situation trying to use Ajax in Wordpress.
1. The file to be called has only a tiny code like: <?php echo "Whatever" ?>
2. it is to be called to and by button onclick:
<button id="ajaxbtn" onclick="showPopup()" class="btn-shape"></button>
<div id="ajax-input"></div>
3. Functions.php
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data() {
wp_localize_script('ajax-wear', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
ob_start();
get_template_part(get_stylesheet_directory_uri() . 'extra-wear' );
$result = ob_get_contents();
ob_end_clean();
$return = array('content' => $result);
wp_send_json($return);
wp_die();
}
4. Jquery
jQuery("#ajaxbtn").click(function() {
jQuery.ajax({
type: 'post',
dataType: 'json',
url: myajax.ajax_url,
data: {
action: 'tablo'
},
success: function(response) {
jQuery('#ajax-input').html(response.content);
}
});
});
5. Present output.
In the console there is information that XHR finished loading: Post "http//....." but nothing is really posted.
Has someone any idea what could be wrong with that code? my quess is point. 3
Any good advise highly appreciated.
get_stylesheet_directory_uri() is apparently not a correct way to build a path to call a file in that function. Once amended the content returned.
For what I see, you have two problems:
the dataType: 'json' parameter, most probably because you're not sending data in a json format
the "response.content" should be just "response"
Also, no idea if the URL you pass in "myajax.ajax_url" has been declared before this bit of code?
One more thing, "success" is depreciated since jQuery 1.8, and you should now use done() instead.
With all of that considered, how about trying this and see if it works?
$.ajax({
type: 'post',
url: 'path/to/your-ajax-file.php',
data: { action: 'tablo' }
}).done(function(response) {
console.log(response);
$('#ajax-input').html(response);
});
I added a console.log(response); line in the function so you can also see the result in your JavaScript console, remove it once your script works!
Related
I've been reading questions about this problem for a little over a week now, and have tweaked my code to try every answer but have not found a working solution yet. I created a very basic plugin and at this point, I'm just trying to get the response to come through. Here's what I have starting with the main php file:
<?php
add_action('init', 'letsgo');
function letsgo() {
wp_register_script('profile', plugin_dir_url(__FILE__ ) . 'js/profile.js', array('jquery'));
wp_localize_script('profile', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
wp_enqueue_script('profile');
}
function tecprofile() {
$result = array(
'verify' => 'yes'
);
echo json_encode($result);
die();
}
add_action('wp_ajax_tecprofile', 'tecprofile');
add_action('wp_ajax_nopriv_tecprofile', 'tecprofile');
?>
And profile.js:
$(document).ready(function() {
$.ajax({
type: "post",
url: myAjax.ajaxurl,
data: {action: 'tecprofile'},
dataType: 'json',
success: function(response){
console.log(response.verify);
},
error: function(xhr, status, error) {
console.log('error');
}
});
});
All I get in the console is "error."
Any advice or help would be huge, thanks!
I am trying to make an AJAX call on Wordpress but it is giving me an 400 error on admin-ajax.php. I think I have all the enqueues actions correctly setup. Maybe I have still missed out one tiny error. Please help.
I have double-checked that the location of admin-ajax.php and the .js file are correct.
I have also tried enqueuing the .js file directly without registering it first, and calling admin-ajax.php directly at without the array.
I have the following error:
POST https: .../wp-admin/admin-ajax.php 400
jQuery.ajax({ <- this is the line where the error occurs).
The AJAX call has not been sent.
functions.php
add_action( 'wp_enqueue_scripts', 'lp_load_scripts' );
function lp_load_scripts() {
wp_register_script( 'lp-script',get_stylesheet_directory_uri(). '/inc/js/admin.js', array('jquery'), NULL, true );
wp_enqueue_script('lp-script');
wp_localize_script( 'lp-script', 'lp_ajax', array('ajaxurl'=>admin_url( 'admin-ajax.php' )) );
}
add_action( 'wp_ajax_list_papers', 'list_papers' );
add_action( 'wp_ajax_nopriv_list_papers', 'list_papers' );
function list_papers() {
$data = $_POST['key'];
echo($data);
wp_die();
}
admin.js
jQuery(document).ready(function($) {
jQuery('.find-paper').on('click',(e)=>{
var jsondata = JSON.stringify({
key: "listpapers",
urn: $('#urn').val(),
action: "list_papers",
});
console.log(jsondata);
jQuery.ajax({
url: lp_ajax.ajaxurl,
type: "post",
data: jsondata ,
success: function(response){
console.log(response);
},
error: function(e) {
console.log(e);
},
})
})
})
HTML
<input type="text" name="urn" id="urn">
<input type="button" class="find-paper" id="find-paper" value="find papers">
OK. I finally solve the problem.
** Do NOT JSON.stringify the data object. **
Also, no need to add dataType: 'json' either.
Error 400 has now gone.
I have written a jQuery function using jsPDF to convert a form to PDF, I have then added an ajax command with the intention of saving the generated PDF to the server.
However, when I click submit, the page appears to be completing an action. but, when I look at console I see:
POST website.com/wp-admin/admin-ajax.php 400 (bad request)
and I cannot figure out where my code has went wrong.
I have registered my JS and used wp_localize in functions.php:
function ASAP_scripts() {
wp_register_script('js-pod', get_stylesheet_directory_uri() . '/js/POD.js', array('jquery'),'1.1', true);
wp_enqueue_script('js-pod');
wp_localize_script( 'js-pod', 'jspod',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'ASAP_scripts' );
I have also added my ajax commands again in functions.php
add_action( 'wp_ajax_my_ajax_request', 'so56917978_upload_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_request', 'so56917978_upload_callback' );
function so56917978_upload_callback() {
if ( ! empty( $_POST['data'] ) ) {
$data = base64_decode($_POST['data']);
file_put_contents( "get_stylesheet_directory_uri() . '/POD/pod.pdf' ", $data );
echo "success";
} else {
echo "No Data Sent";
}
die;
}
My jQuery:
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas)
{
console.log("#submit clicked");
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(img, 'JPEG',20,20);
var file = doc.output('blob');
var pdf = new FormData(); // To carry on your data
pdf.append('mypdf',file);
$.ajax({
url: '/wp-admin/admin-ajax.php', //here is also a problem, depends on your
data: {
action: 'so56917978_upload', // Action name.
data: pdf,
},
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
}).done(function(data){
console.log(data);
});
}
});
}
Any help in solving this would be great. I have seen similar questions on here but I feel as though I have covered all the bases which they discuss and genuinely cannot see my issue
Update...
Update...
I have changed MY JS slightly, it seems to work better and more as expected, however, I am still getting `no data sent. So the ajax request seems to be working. but, it appears that there may be something in the PHP which is stopping it from completing?
JS
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas)
{
console.log("#pdfsubmit clicked");
function html() {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4' );
doc.addImage(img, 'JPEG', 20, 20);
var pdf = doc.output('blob');
$.ajax({
url: jspod.ajax_url,
type: 'post',
async: false,
contentType: 'application/json; charset=utf-8',
data:{
data: pdf
action:'so56917978_upload'
},
dataType: 'json'
});
}
});
}
}
PHP:
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload' );
function so56917978_upload() {
if ( ! empty( $_POST['action'] ) ) {
$data = base64_decode($_POST['action']);
file_put_contents( get_template_directory() . '/POD/pod.pdf' , $data );
echo "success";
} else {
echo "No Data Sent";
}
die();
}
You have few errors in the code.
In the JS code, url needs to be jspod.ajax_url. Also, the action needs to be my_ajax_request.
Not sure why you have double quotes in file_put_contents function. Also you might want to use get_template_directory function to get the path rather than URI?
Hope it helps.
just change you action hooks with the name which you have used in ajax request action: 'so56917978_upload'
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload' );
also it will be good if you use localize variable instead of hard coding the url in ajax url: '/wp-admin/admin-ajax.php' although it has nothing to do with your problem but its good practice.
EDIT -
you also need to append action in FormData and then in ajax you need to pass that pdf object in data object so basically your code will look like this
pdf.append('action', 'so56917978_upload');
$.ajax({
url: jspod.ajax_url, //here is also a problem, depends on your
data: pdf,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
}).done(function (data) {
console.log(data);
});
where pdf.append('action', 'so56917978_upload'); will append the action in your FormData object.
data: pdf, and this field in ajax will hold you pdf data object.
PHP
function customFilter_wpcf7_is_email() {
$emailIsValid = $_REQUEST['emailValid'];
echo 'WHAT';
echo 'HI ' . $emailIsValid;
wp_die();
}
add_action( 'wp_ajax_nopriv_customFilter_wpcf7_is_email', 'customFilter_wpcf7_is_email' );
add_action( 'wp_ajax_customFilter_wpcf7_is_email', 'customFilter_wpcf7_is_email' );
PHP for localizing the ajax url (I placed this under my wp_enqueue_scripts section)
wp_localize_script( 'screenr-child', 'wpcf7_EmailVerify', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
JQUERY:
$.ajax({
url: wpcf7_EmailVerify.ajax_url,
type: 'POST',
data: {
action: 'customFilter_wpcf7_is_email',
emailValid: emailValid,
},
success: function( response ) {
console.log('ajax success');
}
});
For reference, wpcf7_EmailVerify.ajax_url returns "https://whatevermysiteurlis/wp-admin/admin-ajax.php" so the url is fine.
EDITS:
I am also seeing "ajax success" in my console log.
the ajax code is part of a function that's called by a form input change event, and this part is working based on previous tests
Help would be appreciated, thanks!
Is it possible to send jQuery variable to function.php, and use it in some php function? Via AJAX or probably.
Theme related, not using a plugin.
Eg.
I have some post CSS classes added on 'client side' via jQuery on click.
Can I use this classes on 'server side' so I can pass them in any page of my theme?
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so18550905_enqueue_scripts' );
function so18550905_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR SCRIPT FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so18550905_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so18550905_wp_ajax_function' );
function so18550905_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Yes you can use AJAX to send your jQuery variable. (or any Javascript Variable)
Simply do a JSON.stringify(any-Variable-Here) then you get a corresponding string.
Send the value via AJAX to any php file like:
var toBeSent = JSON.stringify($($('#selector')[0]).attr('class'));
$.ajax({
type: "POST",
url: 'function.php',
data: toBeSent,
success: function(data){ // any action to be performed after function.php returns a value.
},
dataType: 'text'
});
NOTE: I've stringified the items here so that you can access the variables on the server side by doing simple splits.
Sure you can
$('element').click(function(e){
e.preventDefault();
var el = $(this);
//do stuff on click
//send this elements class to the server
$.ajax({
url: "some.php",
data: {
class: el.attr('class')
},
success: function(r){
alert("class name sent successfully to some.php");
}
});
});
another option for you could be $.post()
$(document).ready( function() {
$('#myDiv').click(function(){
var myClass = $(this).attr('class');
var url = 'page.php';
$.post(url, { class: myClass })
.done( function() {
alert('class sent to ' + url);
});
});
});