Reputation: 21
I have asked a question on Wordpress Stack Exchange about this, but I haven't had any replies. I have updated the question a few times as I have learn't things on the way, so perhaps it wasn't worth answering in its original form, but now I'm stuck. Apologies if I shouldn't be posting it here - I shall remove if asked. The original is here:
https://wordpress.stackexchange.com/q/375553/195300
I am using a secondary api to provide content to a WordPress site. I can log in to that api using a form, some AJAX and some php. But, although the response is a 200 OK from my api, WordPress always returns a 404 Not Found, as shown below.
Since I am getting the correct responses from my own api, can I modify the responses I am getting from Wordpress, so that my AJAX can read it and do something. In the console I see the response below. It would all be fine if it wasn't appending a lot of HTML to my own generated {"success":true} response.
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (a)
always: ƒ ()
complete: ƒ ()
done: ƒ ()
error: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (a)
overrideMimeType: ƒ (a)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (a)
readyState: 4
responseText: "{"success":true}
↵<!DOCTYPE html>
↵<html lang="en-"
setRequestHeader: ƒ (a,b)
state: ƒ ()
status: 404
statusCode: ƒ (a)
arguments: null
caller: null
length: 1
name: "statusCode"
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: jquery.js?ver=1.12.4-wp:4
[[Scopes]]: Scopes[3]
statusText: "Not Found"
success: ƒ ()
then: ƒ ()
__proto__: Object
I tried using status_header();
in my php but that didn't work.
I also wondered if the problem related to this: jQuery Ajax returning 404 Error, but correct Response
If so, I'm not sure I know what to do...
Upvotes: 1
Views: 94
Reputation: 21
Seems odd to answer my own question, but in case it is of use to someone, this is the answer.
To make an ajax call to a plugin, and receive the response correctly you must register that endpoint with the plugin. This allows you to sidestep the protection Wordpress is putting in your way. I'm not sure if links to YouTube are allowed/accepted on here, but there is an excellent video here. I will remove if this is considered bad practice.
php for plugin
add_action ( 'rest_api_init', 'add_callback_url_endpoint' );
function add_callback_url_endpoint(){
register_rest_route(
'my_route/',
'receive_callback',
array(
'methods' => 'POST',
'callback' => 'my_receive_callback'
)
);
}
function my_receive_callback($request_data){
$data = array();
$params = $request_data -> get_params();
$index = $params['index'];
if(isset($index)){
$data = array(
'index' => $index,
'status' => 'OK'
);
}else{
$data = array(
'status' => 'Not OK'
}
return $data;
}
Upvotes: 1