I am trying to save a PDF to server on Wordpress, When I press submit on the form and look at Console I get the messages:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
and
jquery-2.2.4.min.js:4 POST https://eazyfreight.co.uk/wp-admin/admin-ajax.php 400
My Code:
PHP:
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload' );
function so56917978_upload() {
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();
}
JS
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas){
console.log("#pdfsubmit clicked");
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: false,
processData: false,
data:{
data: pdf,
action:'so56917978_upload',
},
dataType: 'json',
});
}
});
}
Any help sorting the error and then sending the document to the server would be much appreciated
Im not sure but it seems like your code is fine, i would have done it the same way.
Try updating your jQuery version since you are using a veeery old version..
Related
I want the user to be able to upload html files using ajax from my custom editor block. Wordpress requires all ajax go through admin-ajax.php. My js code is in an external file registered and enqueued in Wordpress. Here is a Wordpress Codex instruction from https://codex.wordpress.org/AJAX_in_Plugins:
Separate JavaScript File
The same example as the previous one, except with the JavaScript on a separate external file we'll call js/my_query.js. The examples are relative to a plugin folder.
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
With external JavaScript files, we must first wp_enqueue_script() so they are included on the page. Additionally, we must use wp_localize_script() to pass values into JavaScript object properties, since PHP cannot directly echo values into our JavaScript file. The handler function is the same as the previous example.
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
Here is my PHP:
if (isset ( $_POST["test"] ) ){
echo 'test working';
}
if ( isset ( $_FILES["renee_wip_upload"] ) ){
echo 'test2';
}
And here is my js function:
function fileSubmit(e) {
e.preventDefault();
if(typeof(files2) !== "undefined"){
//ajax using post() works fine which means the php side is OK
renee_wip_ajax_object.braft_wip_upload_value = 'test';
var data2 = {
'action': 'renee_wip_block_ajax',
'test': renee_wip_ajax_object.braft_wip_upload_value
};
jQuery.post(renee_wip_ajax_object.ajax_url, data2, function(response) {
console.log('response test: ', response);
}).fail(function(response) {
console.log('Error: ' + response.responseText);
});
//It seems $_FILES never gets populated
data = new FormData();
data.append('action', 'renee_wip_block_ajax');
for (var i = 0; i < files2.length; i++) {
var file = files2[i];
data.append('renee_wip_upload[]', file, file.name);
}
jQuery.ajax({
success: function(data){
console.log('data: ', data);
},
error: function(err){
throw err;
},
type: "post",
url: renee_wip_ajax_object.ajax_url,
data: data,
dataType: "html",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
}).done(function(msg){
console.log('done: ', msg);
}).fail(function(err){
throw err;
});
}
}
Man, I am blind as hell. It was: data.append('braft_wip_upload[]', file, file.name); but should be: data.append('renee_wip_upload[]', file, file.name); I even corrected the mistake in edit, but forgot to do it in my code.
Using AJAX to send a PDF created with jsPDF to server.
When I run the script and use Inspect > Network and check admin-ajax.php I se at the bottom Request Payload [object object]
From my research, as far as I can tell this means that something is being sent to the server but it cannot decode it so I get > No Data Sent
I cannot see anything wrong with my code but if someone can help to debug, that would be great
The code I have used:
JS:
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas){
console.log("#pdfsubmit clicked");
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4' );
doc.addImage(img, 'JPEG', 20, 20);
var pdf = btoa(doc.output());
$.post({
url: jspod.ajax_url+'?action=so56917978_upload',
contentType: false,
processData: false,
data:{
data: pdf
},
/*dataType: 'json',*/
success: function(response, status) {
alert(response);
}
});
}
});
}
functions.php - register Script:
function ajaz_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( 'admin_enqueue_scripts', 'ajax_scripts' );
PHP Script:
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload_callback' );
add_action( 'wp_ajax_nopriv_so56917978_upload', '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";
}
echo 'got there';
die();
}
If anyone could advise as to how to sort the [object object], it would be much appreciated
UPDATE
I have changed my JS to:
function make_product_sheet() {
console.log("#pdfsubmit clicked");
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML(document.getElementById("product_sheet"), function() {
var file = btoa(pdf.output());
var formData = new FormData();
formData.append('data', file);
$.ajax({
url: jspod.ajax_url+'?action=so56917978_upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
}
And I got a success message. I then checked the folder that the PDF should have been sent to and nothing is there...
I checked the NEtwork tab of inspect element and at the bottom - formData it looked to be an extremely long base64 text string.
I have no idea what to do from here, my php should decode the base64 and save bit it looks asthough it has done neither
You could use the FormData object to mock a HTML form, and then post this.
This will result in the file being available in PHP's $_FILES.
var pdf = doc.output('blob');
var formData = new FormData();
formData.append('data', pdf);
$.ajax({
url: jspod.ajax_url + '?action=so56917978_upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
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.
I have been through 21 different posts on this site and many others on google, currently on page 13 and i'm actually about to cry. I am a junior developer and I am really struggling to get this to work. For some reason I can't seem to grasp it.
I am trying to create a plugin that will allow me to upload a blob file to WordPress media library and it's failing miserably.
The plugin structure is like so:
ajax_test/
-- ajax_test.php
-- assets/
-- -- js/
-- -- -- uploader.js
In a file called uploader.js I have this code:
mediaRecorder.addEventListener('stop', function() {
audio.src = URL.createObjectURL(new Blob(recordedChunks));
downloadLink.href = URL.createObjectURL(new Blob(recordedChunks));
downloadLink.download = 'file' + Date.now() + '.wav';
downloadLink.classList.remove('hide');
var blob = new Blob(recordedChunks);
var fd = new FormData();
fd.append('fname', 'test.wav');
//fd.append('data', event.target.result);
fd.append('file', blob);
fd.append('action', 'send_message');
console.log('about to ajax');
$.ajax({
url: ibenicUploader.ajax_url,
type: 'POST',
data: fd,
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
if( data.response == "SUCCESS" ){
console.log('success');
} else {
console.log('error');
}
}
});
console.log('after ajax');
});
And in the ajax_test.php file I have this code:
function ibenic_enqueue() {
wp_enqueue_script( 'ibenic-uploader', plugins_url( 'assets/js/uploader.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'ibenic-uploader', 'ibenicUploader',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'ibenic_enqueue' );
In the console I get
about to ajax
after the ajax
/wp-admin/admin-ajax.php 400 (Bad Request)
Even if I change ibenicUploader.ajax_url, to a full path I get the same error.
Please can someone help me upload this file to wordpress
You will have to logged in to it work as wp_ajax works with logged in user.
add_action("wp_ajax_your_fn", "your_fn");
For visitor use wp_ajax_nopriv
add_action("wp_ajax_nopriv_your_fn", "your_fn");
AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )