WordPress ajax returns 404 bad request? - php

The error is below
POST http://localhost/...../wp-admin/admin-ajax.php 400 (Bad Request)
send # load-scripts.php?c=1…e,utils&ver=4.9.8:4 ajax # load-scripts.php?c=1…e,utils&ver=4.9.8:4 (anonymous) # my-ajax-handler.js?ver=0.1.0:24 i # load-scripts.php?c=1…e,utils&ver=4.9.8:2 fireWith # load-scripts.php?c=1…e,utils&ver=4.9.8:2 ready # load-scripts.php?c=1…e,utils&ver=4.9.8:2
K # load-scripts.php?c=1…e,utils&ver=4.9.8:2
$.ajax({
type: "POST",
url : my_ajax_handler_var.ajaxurl,
data : {
action: 'rc_generate_pa'// "wp_ajax_*" action hook
},
contentType: "application/json; charset=utf-8",
dataType: "json"
,success:function(data) {
//This outputs the result of the ajax request
var pass = JSON.parse( data );
$('#p').val(data);
alert( JSON.parse(data));
},
error: function(errorThrown){
console.log(errorThrown);
}
})
// .done( function( response ) {
// var pass = response;
// $('#p').val(pass);
// })
.fail( function() {
console.log("failed");
});
PHP code for enqueing script and handling request
add_action('admin_enqueue_scripts', 'enqueue_st_page_scripts');
function enqueue_st_page_scripts() {
wp_register_script('my-ajax-handler', $plugin_url .'js/my-ajax-handler.js', array('jquery'), '0.1.0', true );
wp_enqueue_script(array('my-ajax-handler'));
$vars = array('ajaxurl' => admin_url('admin-ajax.php'));
wp_localize_script('my-ajax-handler', 'my_ajax_handler_var', $vars);
}
add_action( 'wp_ajax_rc_generate_pa', 'rc_generate_p' );
function rc_generate_p(){
$pass = (string)wp_generate_password(8, true, false);
echo $pass;
header('Content-Type: application/json');
$results = json_encode($pass);
echo $results;
exit;
}
I have seen similar problems on this site and tried the solution,but no success. I am new to WordPress plugin development.

Main Issue
The problem is in the $.ajax() call, where you should've not set the contentType to JSON:
$.ajax({
url: my_ajax_handler_var.ajaxurl,
contentType: "application/json; charset=utf-8",
...
});
because that way (from the PHP side), the action (i.e. rc_generate_pa) is not available in $_REQUEST['action'] which WordPress uses to determine the AJAX action being called, and when the action is not known, WordPress throws the 400 Bad Request error.
So to fix the error, just remove the contentType property: (or use something other than the JSON type)
$.ajax({
url: my_ajax_handler_var.ajaxurl,
// Don't set contentType
...
});
Second Issue
In your $.ajax()'s success callback, don't use the JSON.parse( data ); and here's why:
When dataType is json, jQuery will automatically parse the response output into a JSON object — or it could also be a string; see point #2 below.
In the (PHP) rc_generate_p() function, the $pass is neither an array nor object/class; hence in the $.ajax()'s success callback, the data is actually an invalid JSON string and JSON.parse( data ) will throw a JavaScript syntax error.
So your $.ajax()'s success could be rewritten into:
success: function(data){
$('#p').val(data);
console.log(typeof data); // test
})
Third Issue
In your rc_generate_p() function, remove the echo $pass;, or you'll get a JavaScript syntax error — your AJAX call is expecting a JSON response, and yet that echo part invalidates the JSON.
I know you probably added that to debug the 400 error; but I thought I should just remind you about removing it.. :)
And you might want to consider using wp_send_json() like so, where you don't need to call exit, die, or wp_die():
function rc_generate_p() {
$pass = wp_generate_password( 8 );
wp_send_json( $pass );
}

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Wordpress admin-ajax.php returns 0 even if using wp_die()

I'm trying to filter my posts with a simple ajax call, but cant get it to work because my admin-ajax.php call always returns 0.
There are many issues facing this problem but they are mostly fixed by adding wp_die(),
which is not solving my issue.
Ajax Call:
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'filter_projects',
},
success: function(res) {
$('.project-tiles').html(res);
console.log(res);
}
})
PHP function:
function filter_projects() {
echo "<p>test</p>";
wp_die();
}
add_action('wp_ajax_filter_projects', 'filter_projects');
add_action('wp_ajax_nopriv_filter_projects', 'filter_projects');
The PHP function is registered correctly as I'm getting a 200 on it, but it's always returning 0 and 'success'.
What I already tried:
WP_DEBUG=1 --> no Error
Check dev console --> no Error
Check network --> 200 on admin-ajax.php call but received "0"
Tried die() and exit instead of wp_die()
I dont know how to debug this any further as it is not returning any errors.
Does anyone have an idea?
instead of echo directly your HTML, try manipulating the results with JSON so you can get better results for evaluating your test.
How would I do the same test you posted (using direct JS instead of JQUERY):
let xhr = new XMLHttpRequest();
xhr.open('POST', "/wp-admin/admin-ajax.php", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var params = 'action=filter_projects';
xhr.onreadystatechange = () => {
if(xhr.readyState == 4) {
// RETURN OK
if(xhr.status == 200) {
console.log(xhr.responseText); // TEXT RESPONSE
console.log(JSON.parse(xhr.responseText)); // JSON RESPONSE
// HTTP ERROR
}else{
console.log("SOME ERROR HTTP");
console.log(xhr.responseText);
}
}
};
xhr.send(params);
PHP CODE:
function filter_projects() {
$content = "test";
$data = array('success' => "200", 'content' => $content);
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;
wp_die();
}
add_action('wp_ajax_filter_projects', 'filter_projects');
add_action( 'wp_ajax_nopriv_filter_projects', 'filter_projects' );

Ajax Call Back and Laravel

I have created an API which my AJAX post send values to it. AJAX does post and my laravel API does process the values. My issues is with the callback returning the value back to my AJAX post. My AJAX doesn't return the results in the success section when I do console log. I would like the results from my api to can use data to make my condition. At the moment, the console log doesn't even return a value. But in my chrome inspector under preview it shows the response from my API but not in the success section.
AJAX
var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
$.ajax({
type: 'POST',
url: processUrl,
data: {"name": fname,"surname": lname},
dataType: 'json',
success: function(res){
console.log(res);
if(res.length >= 1){
$('#display').val(res.name);
}
}
});
PHP
public function checkResults(Request $request){
$name = $request->name." ".$request->surname;
$result = array();
$result['name'] = [$name];
return response()->json($result,201);
}
For first it will be good to return with 200 OK response code (instead of 201).
Note: If you want to just immediately get the answer for your question only, you can see the last part of this answer (usage of "done/fail" construct instead of "success/error").
Additional:
There is many patterns which are used by Client(Frontend)<->API<->Server(Backend) developers.
Approximately all APIs built without any 500 server error codes. But there is exists also many differences between APIs structures.
One of them is to send response like this (this is the only one example of response):
return response()->json([
'success' => true, // true or false
'message' => "Message about success!",
], 200); // 200, 401, 403, 404, 409, etc
The other approach is to always sending 200 OK, but message can be also about error:
return response()->json([
'success' => false, // true or false
'code' => 404,
'message' => "Resource not found!",
], 200);
This kind of methods will written under try{}catch() and will return only 200, but that messages can imitated also as an error (as in example).
The other (appropriate approach for you) is to change your Frontend AJAX functionality like this:
$.ajax({
type: 'POST',
url: processUrl,
data: {
{{--_token: "{{ csrf_token() }}",--}}
name: fname,
surname: lname
},
dataType: 'json'
}).done(function(res) {
console.log(res);
if(res.length >= 1) {
$('#display').val(res.name);
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error: " + textStatus);
});
AJAX .done() function replaces method .success() which was deprecated in jQuery 1.8. This is an alternative construct for the success callback function (like before: "success: function(){...}").
AJAX .fail() function replaces method .error() which was deprecated in jQuery 1.8. This is an alternative construct for the complete callback function (like before: "error: function(){...}").
Note: .error() callback is called on HTTP errors, but also if JSON parsing on the response fails. This is what's probably happening if response code is 200/201 but you still are thrown to error callback.
I believe this is happening because you are sending status code 201 (Created), but you need to send status code 200 (OK) to trigger the success callback.
public function checkResults(Request $request){
$name = $request->name." ".$request->surname;
$result = array();
$result['name'] = [$name];
return response()->json($result,200);
}
I couldn't find it specifically in the jQuery docs, but this SO question addresses it.
Due to the asynchronous nature of Ajax calls, do not put them in the normal execution flow of your program. See this post to get more insight.
A quick fix for your problem is to include the ajax call in a function and call that function anytime you want to interact with the server asynchronously.
var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
ajaxCall();
function ajaxCall() {
$.ajax({
type: 'POST',
url: processUrl,
data: {"name": fname,"surname": lname},
dataType: 'json',
success: function(res){
console.log(res);
if(res.length >= 1){
$('#display').val(res.name);
}
},
error: function() {
console.log('error');
}
});
}
In addition, include an error function in the ajax call settings to handle cases where the ajax request fails. See this answer for alternative styles of doing this.

having issue on Accessing Ajax Post data on PHP

I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.

How can I access my PHP variables when calling ajax in jQuery?

I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );

Categories