Creating a Reddit post
The next piece of the puzzle is to create a post for my subreddit using my application.
For this, Reddit requires key pieces of info or the request will fail. First of all, the 'sr' field is needed, stating the subreddit you wish to post in. Without this, Reddit would not know where to post the content you wish.
Secondly, a 'kind' is needed. This could be either 'link', signifying a link to an external source such as a news article, or 'self'. The latter option is for posting a self post (by you) with a title and body - the regular format for a post.
Lastly, the title and text of the post is required (obviously). Since this request is being made by AJAX there must be a way to fetch the data that the user has entered in to the request. This stumped me for a while, as my go-to was to use an HTML form, but this system is not synonymous with AJAX, as they achieve the same outcome in a different way. So for this, input boxes with specific ID's are used. This way, we can easily fetch the data from the input boxes.
The request is seen below.
Another tip for future AJAX requests is that when clicking a submit button, the webpage's default behavior is to reload. To circumvent this event, Jquery allows you to preventdefault() which will stop this reload from happening.
Also, this request requires a 'user-agent' which describes a bit about the application/user making the request. In this case, your Reddit username and display name is sufficient.
Should this request be a success, the response will be logged, and should show a successful message like below:
And to confirm this was a success, peeking in the network traffic will provide you with the response from Reddit, containing the post URL.
Which if followed, will show the post:
Success!
Comments
Post a Comment