I'll explain the basics:
jQuery.post
= You want to post some data to your endpoint
ajaxurl
= your endpoint address. Typically a API
data
= the data you want to send to your endpoint along with the request.
function(response)
is where you handle the response from the endpoint.
So lets go through the code. First you call post
to your endpoint / API with the data
you want to post. Then you provide a callback (in your case a function) to handle the response the endpoint / API provides you.
In your case it looks like if the endpoint responds with 1
, you have successfully posted your data. If the endpoint responds with 2
, you have posted data and want to reload the site. If the endpoint does NOT respond with either 1
or 2
, it failed to post.
To help you understand the basics of jQuery post:
A well-written API / endpoint should respond with the correct HTTP status codes and status messages and it should be fairly easy to notice when data was posted correctly and when an error occurred.
I don't think your endpoint responds any good. response == 1
or response == 2
is not by any means clear and easy to understand.
A better way of handling success and errors is to use the done
and fail
handlers of jquery post (more on this below).
$.post( "test.php" );
This will completely ignore the response from calling the endpoint. I.e. you don't want to handle either success or error. PLEASE DO NOT USE THIS. You should handle success and error!
$.post( "test.php", function( data ) {
//Do something now
});
This will do whatever you provide in the function when the endpoint has sent its response.
$.post( "example.php", function() {
//You successfully reached the endpoint
console.log( "success" );
})
.done(function() {
//Handle success here!
})
.fail(function() {
//Handle error here
})
This is probably the preferred way of handling both success and errors. It's pretty clear that if you reach the fail
, it has failed. Both easy to read the code and easy to understand jquery post!
The examples above is copied from the jquery documentation.
Note that the previous handlers for done
and fail
was success
and error
, but success
and error
is deprecated and removed in jQuery 3.0!
So if you have jQuery version < 3.0 you need to find out if you need to use the new or old syntax, or if you need to update jQuery maybe?
Hope this explains enough to make you understand the basics, and to help you get further. I highly suggest you read the jQuery.post documentation here. I think you should also read the w3schools documentation here.