0

I ran into very strange issue,where my code is not sending file. At the same time, there is no errors / warnings & console logs gives nothing.

I get HTTP 201 status, but my API catches nothing & DB entry gets created, but all with NULL field.

Almost 3 developers, scratched heads, but no one found any issue.

Here is the code for upload :

function startAll() {
$('#addTopicMediaForm').on('submit', function (event) {
  event.preventDefault();
  const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));

  const file = $('#topic_media')[0]?.files[0];
  console.log(file);

  //  const file = document.querySelector('#topic_media');



  const fileName = file?.name;
    console.log(fileName);


  if (dataArray.filter((i) => i.value).length < 4 || !file) {
    swal('Error', 'Please fill all required field', 'error');
    return;
  }

  const formData = new FormData();
  dataArray.forEach(({ name, value }) => {
    formData.append(name, value);
  });
  formData.append('status', true);
  if (file) {
    formData.append('topic_media', file, fileName);
  }
  axios
    .post(`${baseUrl}/topic-media/`, formData)
    .then((response) => {
      console.log(response);
      console.log(file);
      console.log(fileName);
      swal('Success', 'Topic-Media added successfully', 'success');
    })
    .catch((err) => {
      const errorData = err?.response?.data;
      if (Object.keys(errorData).length > 0) {
        const allErrors = serializeErrorArray(err?.response?.data);
        swal(allErrors[0].name, allErrors[0].errors[0], 'error');
      } else {
           swal('Error', 'Something went wrong! Try again!', 'error');
          }
        });
    });
  }


});

Full HTML CODE is here :

        $(document).ready(function () {
          function fetchGrades() {
            axios
              .get(`${baseUrl}/grade/`)
              .then((res) => {
                const allGrades = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.grade_name}</option>`;
                  })
                  .join(' ');
        
                $('#grade_name').html(allGrades);
                fetchSubject();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchSubject() {
            axios
              .get(`${baseUrl}/subject/`)
              .then((res) => {
                const allSubject = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.subject_name}</option>`;
                  })
                  .join(' ');
        
                $('#subject_name').html(allSubject);
                fetchChapter();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
        
          function fetchChapter() {
            axios
              .get(`${baseUrl}/chapter/`)
              .then((res) => {
                const allChapters = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.chapter_name}</option>`;
                  })
                  .join(' ');
        
                $('#chapter_name').html(allChapters);
                fetchTopics();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchTopics() {
            axios
              .get(`${baseUrl}/topic/`)
              .then((res) => {
                const allTopics = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.topic_name}</option>`;
                  })
                  .join(' ');
        
                $('#topic_name').html(allTopics);
                fetchSubTopics();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchSubTopics() {
            axios
              .get(`${baseUrl}/subtopic/`)
              .then((res) => {
                const allSubTopics = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.subtopic_name}</option>`;
                  })
                  .join(' ');
        
                $('#subtopic_name').html(allSubTopics);
                startAll();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
        
          fetchGrades();
        
          function startAll() {
            $('#addTopicMediaForm').on('submit', function (event) {
              event.preventDefault();
              const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));
        
              const file = $('#topic_media')[0]?.files[0];
              console.log(file);
        
             //  const file = document.querySelector('#topic_media');
              //  console.log(file);
        
        
              const fileName = file?.name;
                console.log(fileName);
        
        
              if (dataArray.filter((i) => i.value).length < 4 || !file) {
                swal('Error', 'Please fill all required field', 'error');
                return;
              }
        
              const formData = new FormData();
              dataArray.forEach(({ name, value }) => {
                formData.append(name, value);
              });
              formData.append('status', true);
              if (file) {
                formData.append('topic_media', file, fileName);
              }
              //axios
               // .post(`${baseUrl}/topic-media/`, formData)
        
        
                axios.post(`${baseUrl}/topic-media/`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
        
        
                .then((response) => {
                  console.log(response);
        
                  swal('Success', 'Topic-Media added successfully', 'success');
                })
                .catch((err) => {
                  const errorData = err?.response?.data;
                  if (Object.keys(errorData).length > 0) {
                    const allErrors = serializeErrorArray(err?.response?.data);
                    swal(allErrors[0].name, allErrors[0].errors[0], 'error');
                  } else {
                    swal('Error', 'Something went wrong! Try again!', 'error');
                  }
                });
            });
          }
        
        
        });
        
        

Full JS code is here :

        $(document).ready(function () {
          function fetchGrades() {
            axios
              .get(`${baseUrl}/grade/`)
              .then((res) => {
                const allGrades = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.grade_name}</option>`;
                  })
                  .join(' ');
        
                $('#grade_name').html(allGrades);
                fetchSubject();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchSubject() {
            axios
              .get(`${baseUrl}/subject/`)
              .then((res) => {
                const allSubject = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.subject_name}</option>`;
                  })
                  .join(' ');
        
                $('#subject_name').html(allSubject);
                fetchChapter();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
        
          function fetchChapter() {
            axios
              .get(`${baseUrl}/chapter/`)
              .then((res) => {
                const allChapters = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.chapter_name}</option>`;
                  })
                  .join(' ');
        
                $('#chapter_name').html(allChapters);
                fetchTopics();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchTopics() {
            axios
              .get(`${baseUrl}/topic/`)
              .then((res) => {
                const allTopics = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.topic_name}</option>`;
                  })
                  .join(' ');
        
                $('#topic_name').html(allTopics);
                fetchSubTopics();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
          function fetchSubTopics() {
            axios
              .get(`${baseUrl}/subtopic/`)
              .then((res) => {
                const allSubTopics = res.data
                  .map((item) => {
                    return `<option value="${item.id}">${item.subtopic_name}</option>`;
                  })
                  .join(' ');
        
                $('#subtopic_name').html(allSubTopics);
                startAll();
              })
              .catch(() => {
                swal('Error', 'Error occurred during fetching data', 'error');
              });
          }
        
          fetchGrades();
        
          function startAll() {
            $('#addTopicMediaForm').on('submit', function (event) {
              event.preventDefault();
              const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));
        
              const file = $('#topic_media')[0]?.files[0];
              console.log(file);
        
             //  const file = document.querySelector('#topic_media');
              //  console.log(file);
        
        
              const fileName = file?.name;
                console.log(fileName);
        
        
              if (dataArray.filter((i) => i.value).length < 4 || !file) {
                swal('Error', 'Please fill all required field', 'error');
                return;
              }
        
              const formData = new FormData();
              dataArray.forEach(({ name, value }) => {
                formData.append(name, value);
              });
              formData.append('status', true);
              if (file) {
                formData.append('topic_media', file, fileName);
              }
              //axios
               // .post(`${baseUrl}/topic-media/`, formData)
        
        
                axios.post(`${baseUrl}/topic-media/`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
        
        
                .then((response) => {
                  console.log(response);
        
                  swal('Success', 'Topic-Media added successfully', 'success');
                })
                .catch((err) => {
                  const errorData = err?.response?.data;
                  if (Object.keys(errorData).length > 0) {
                    const allErrors = serializeErrorArray(err?.response?.data);
                    swal(allErrors[0].name, allErrors[0].errors[0], 'error');
                  } else {
                    swal('Error', 'Something went wrong! Try again!', 'error');
                  }
                });
            });
          }
        
        
        });
        
        
        
        
user3670334
  • 111
  • 6
  • If `console.log` gives nothing and you have `console.log(fileName);` then `$('#topic_media')[0]?.files[0]` isn't finding the file (which suggests that doesn't select a file input or you haven't picked a file using it). – Quentin Feb 16 '22 at 08:21
  • Console.log(fileName); - si showing filename – user3670334 Feb 16 '22 at 08:48
  • html code is here : – user3670334 Feb 16 '22 at 08:49
  • 1
    Have you checked the Network tab to see what the payload is? It's entirely possible that the data is being sent but the server side code is failing to parse it. – Quentin Feb 16 '22 at 09:17
  • Does this answer your question? [How to upload file using javascript?](https://stackoverflow.com/questions/29910490/how-to-upload-file-using-javascript) – Peter Krebs Feb 16 '22 at 09:22

0 Answers0