Ajax request does not get executed

I am trying to upload both form data and files to the database using a combination of JavaScript, JQuery Ajax and PHP, i want to do this using one ajax request. For some reason i can’t seem to get it to work since the ajax request goes straight to my error function instead of the success function.

I have a rather large HTML form so i simplified it a bit to give a small example of how its build. I am also using a submit/save button outside of the of the form.

 <form method="post" enctype="multipart/form-data" class="flex" id="hours-form" name="hours-form">
           <textarea name="comment" class="form-control" id="commentsInput" rows="3"
          placeholder="Vul hier eventuele opmerkingen in over de geregistreerde uren en ritten."></textarea>
           <input name="attachment" type="file" class="custom-file-input" id="attachmentFileInput">
</form>

<button type="button" class="btn btn-sm btn-success ml-auto" id="save-week">Save Week </button>

Once the user presses the Save Week button it will go trough a function called ValidateHours() which is working fine, after that it will go trough a function called SaveWeek() which will check wether or not the save week or submit week button has been pressed (Submit button will lock the week).

$(document).on('click', '#save-week', function () {
    if (ValidateHours()){
        SaveWeek('save');
       }
   });

function SaveWeek(action) {

    if (action === 'submit') {

        Modal("confirmSend", "", "Week indienen",
            "Door op indienen te drukken worden alle uren en ritten ingediend, na deze actie zijn de gegevens niet meer aanpasbaar.",
            "indienen", "annuleren");

        $(document).on('click', '#confirmSendModal #confirm', function () {
            saveWeekLogic();
        });

    } else {
        saveWeekLogic();
    }

    function saveWeekLogic() {

        var form = $('#hours-form');
        var formData = new FormData(form[0]);

        formData += "&request=save-week&type=" + action;

        console.log(form);
        console.log(formData);
      
        // send http request
        $.ajax( {
            type: "POST",
            data: formData,
            dataType: 'JSON',
            contentType: false, 
            processData: false, 
            cache: false,
            success: function (response) {

                console.log('Success', response);

            }, error: function (error){
                console.log('Error', error);
            }

        });

    }

}

In my PHP code i use a switch case system to check what request has been send and what function to execute.

switch ($postArray['request']) {
    case "save-week":
              $this->SaveWeek($postArray, $filesArray);
              break;
}

Any help would be appreciated!

There is no URL in the Ajax request…
and if you send form data the contentType should be application/x-www-form-urlencoded

Thanks for your reply! I added a URL attribute and set it to the path of my php file and changed the contentType, however this didn’t solve my problem since ajax still executes the error function :confused:.

Open your browsers developer tools and check the ajax call and its response in the network tab.

Please try the following:

let fd = new FormData();    
fd.append( 'request', 'save-week');
fd.append( 'type', action);

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  },
  error:  ....
});

Thx for the reply again :+1:, we are getting closer now, the alert shows me that some php variables have a undefined array key and this probably has something to do with the fact that the variable below hasn’t been passed to anything.

let form = $('#hours-form');

I already tried doing something like this:

     let form = $('#hours-form');
     let fd = new FormData(form[0]);

This however gives me a server error and i’m not really sure if this is the right way of doing it.

This looks correct. What server error do you get?

XHRPOSThttps://localhost/uren
[HTTP/1.0 500 server error 890ms]

This is what i see in the console, its a 500 server error

So you have to debug your php code on the server. Try inserting a die(“Test”); at the first line and check if the 500 disappears. If so, move the line down step by step to check when the error occurs.

I figured out it had something to do with a check that checks if a file has been uploaded or not. It’s working now! Thanks for being able to help me out! :rofl: