Skip to content
HumphreyLu6 edited this page Jul 9, 2020 · 1 revision

In this web application, AJAX is used in making GET/POST/PATCH/DELETE requests from React Frontend to Django Backend.

GET Request Example

fetchData = () => {
    axios.get(BE_VISIBLE_POST_API_URL(HOST), { headers: { 'Authorization': 'Token ' + cookie.load('token') } })
      .then(res => {
        publicPost = res.data.posts;
        this.setState({
          isloading: false,
        })
        this.setState({
          PublicPostData: res.data.posts,
        });

      }).catch(function (error) {
        console.log(error);
      });
  }

POST Request Example

handleSubmit = e => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        axios.post(BE_POST_API_URL(HOST),
          {
            title: values.postTitle,
            description: "",
            content: values.postContent,
            contentType: values.Type,
            visibility: values.Visibility,
            visibleTo: "",
            unlisted: false,
          }, { headers: { 'Authorization': 'Token ' + cookie.load('token') } }
        )
          .then(function (response) {
            document.location.replace(FE_USERPROFILE_URL);
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    });
  };

PATCH request Example

handleSubmit = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        axios.patch(BE_SINGLE_POST_API_URL(HOST, id),
          {
            title: values.postTitle,
            description: "",
            content: values.postContent,
            contentType: values.Type,
            isImage: false,
            visibility: values.Visibility,
            visibleTo: "",
            unlisted: false,
          }, { headers: { 'Authorization': 'Token ' + cookie.load('token') } }
        )
          .then(function (response) {
            document.location.replace(FE_USERPROFILE_URL);
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    });
  };

DELETE request Example

showDeleteConfirm = (postId, author) => {
        confirm({
            title: 'Are you sure you want to delete this post?',
            okText: 'Yes',
            okType: 'danger',
            cancelText: 'No',
            onOk() {
                axios.delete(BE_SINGLE_POST_API_URL(HOST, postId), { headers: { 'Authorization': 'Token ' + cookie.load('token') } })
                    .then(function () {
                        document.location.replace(FE_USERPROFILE_URL);
                    })
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

Clone this wiki locally