Using Ajax and PHP in wordpress - php

Hi guys i am new to wordpress and ajax , i use this code for checking an input value before submitting the form :
$j("#ninja_forms_field_75").focusout(function(){
var content = document.getElementById("ninja_forms_field_75").value;
$j.ajax({
url : 'check.php',
data : {'mid':content},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
},
error : function(resp){
alert("some error occured !");
}
});
});
problem is i dont know where shall i put that php file to work with database...
please help me!!!
pardon my english...

Inside your js file write your code above:
javascript.js
$j("#ninja_forms_field_75").focusout(function() {
var content = document.getElementById("ninja_forms_field_75").value,
my_data = {
'action': 'my_action',
'mid': content
};
$j.ajax({
url: ajaxurl,
data: my_data,
type: 'POST',
success: function(resp) {
if (resp == '1') {
//success message or whatever
},
error: function(resp) {
alert("some error occured !");
}
});
});
});
Then the php part begins, I prefer to store it inside the functions.php if it's just one ajax request. If it is more than one create a file like ajax-handler.php and include it inside your functions.php
functions.php
if ( defined( 'DOING_AJAX' ) ) {
include_once( 'ajax-handler.php' );
}
ajax-handler.php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_my_action', 'my_custom_ajax_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_custom_ajax_action' );
function my_custom_ajax_action() {
$result = 'Hello';
wp_send_json( $result );
}

You can try in the functions.php, I have made a form by steps and I do it on functions.php in yout theme directory.

Related

Passing data attribute from Ajax to PHP using Wordpress

I am developing a WordPress plugin and I am trying to pass a variable from function.php(ajax) to pass_userid.php. Both files are inside my plugin folder. I am attempting to pass the data attribute from function.php(ajax) to pass_userid.php but it did not send the data and received error 500.
Plugin structure:
-plugin folder
--function.js
--pass_userid.php
This is my function.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function custom_ajax(){
?>
<script>
jQuery(document).ready(function( $ ) {
$('[data-source-id="13487"]').on("load", function() {
$('[data-source-id="13487"]').contents().find('button.button.ld-gb-gradebook-component-grade-add').click(function() {
var ajaxurl = "https://<?php echo $_SERVER['HTTP_HOST'];?>/wp-content/plugins/gradebook-custom/pass_userid.php";
var user_id = $('[data-source-id="13487"]').contents().find('.ld-gb-gradebook-component-overall-grade').attr('data-user-id');
alert(user_id);
$.ajax({
type: 'POST',
url: ajaxurl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
'action' : 'call_userid',
'userid' : user_id},
success: function(data)
{
console.log("data pass success!");
},
error: function(errorThrown){
console.log("no data pass!");
}
});
});
});
});
</script>
<?php
}
add_action('wp_head', 'custom_ajax');
?>
This is pass_userid.php:
<?php
function call_userid(){
if(isset($_REQUEST)){
$testing = $_REQUEST["userid"];
console.log("Test 123");
}
}
add_action("wp_ajax_call_userid", "call_userid");
add_action("wp_ajax_nopriv_call_userid", "call_userid");
?>

How to properly set up jQuery ajax to upload files in Wordpress?

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.

POST /wp-admin/admin-ajax.php 400 (bad request)

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.

admin-ajax returns an error: admin-ajax.php 400 (Bad Request)

I'm facing an issue and I can't get the reason, I tried to print the variables and check for typo errors, But couldn't find any.
I send an Ajax request to admin-ajax:
function update_order() {
var orderdata = {
action: 'update_order_ajax',
data: 'test'
};
jQuery.ajax({
type: 'POST',
beforeSend: function (jqXHR) {
if (currAjax != null) {
currAjax.abort();
}
currAjax = jqXHR;
},
url: ajaxurl,
data: orderdata,
dataType: 'text',
success: function (response) {
alert(response);
}
}); //end Ajax
} //end function
//Run the above function on submitting a form.
jQuery('#updateOrder').on('submit', function(event) {
event.preventDefault();
update_order();
});
The files are inside a folder inside plugin folder "http://localhost/test/wordpress/wp-content/plugins/update-order/template"
Inside that folder I have:
function update_order_ajax() {
echo $_POST['data']; //That should return 'test'
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_update_order_ajax', 'update_order_ajax' );
But I get:
POST http://localhost/test/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
I searched and viewed many related question and tried to use a custom URL for the admin-ajax.php, Also checked the errors file, But couldn't find any solution.
I checked the admin-ajax.php and I see that it returns 400, When:
$_REQUEST['action'] is empty.
! has_action( 'wp_ajax_' . $_REQUEST['action'] )
! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] )
What is the problem?

Success not being returned from ajax post

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 ;) )

Categories