Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this :

<div class="col-md-4">
 <div class="form-group">
    <label class="control-label col-md-3">Location</label>
    <div class="col-md-9">
        <?php
        $location = array(
            "type" => "text",
            "name" => "location",
            "id" => "location",
            "class" => "form-control"
        );
        echo form_input($location);
        ?>
        <span class="help-block"></span>
    </div>
 </div>
</div>

<div class="col-md-12">
  <div class="form-group">
    <label class="control-label col-md-2">Warehouse</label>
    <div class="col-md-10">
        <?php
        foreach ($tipe as $v):
            echo "<label class='checkbox-inline'><input type='checkbox' name='tipe[]' value='$v->ID_CHECK_LIST'>$v->NAMA_CHECK_LIST</label>";
        endforeach;
        ?>
        <p class="help-block"></p>
    </div>
  </div>
</div>

<div class="col-md-12">
  <div class="form-group">
    <label class="control-label col-md-2">Image If Damage</label>
    <div class="col-md-4">
        <input type="file" multiple="" name="images[]">
        <p class="help-block"></p>
    </div>
  </div>

Now, I am facing an issue with sending data through AJAX. Using $(form).serialized() does not include the $_FILES data, so I have turned to using FormData class. However, FormData is only handling the file and not other input fields. How can I set the data in AJAX parameters to handle both file and other inputs?

This is the jQuery AJAX code snippet:

$('#form').submit(function () {            
        $('#btnSave').text('saving...'); //change button text
        $('#btnSave').attr('disabled', true); //set button disable

        var url;
        var formData = new FormData(this);

        if (save_method === 'add') {
            url = "<?php echo site_url('members/it/Request/ajax_add') ?>";
        } else {
            url = "<?php echo site_url('members/megumi/cek_list_wire_rod/ajax_update') ?>";
        }

        // ajax adding data to database

        $.ajax({
            url: url,
            type: "POST",
            data: formData,
                processData: false,
                contentType: false,
                $('#form').serialize(),
            dataType: "JSON",
            success: function (data)
            {
                 // Handling response    
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                 // Handling errors
            }
        });
        return false;
    });

Any assistance on this matter would be greatly appreciated.

Answer №1

Utilize FormData to handle all the data you want to send, as PHP can process both multipart/form-data and

application/x-www-form-urlencoded
. You can include key-value pairs in the FormData, which will show up as regular $_POST variables, while any files added will be accessible through $_FILES.

For example:

var fd = new FormData();
fd.append('file1', file1);
fd.append('file2', file2, 'newFile2Name.pdf');
fd.append('username', 'password');
fd.append('file_id', file_id);

$.ajax({
    url: url,
    type: "POST",
    data: fd,
    processData: false,
    contentType: false,
    success: function(response) {},
    error: function(xhr, textStatus, errorThrown) {},
    complete: function() {}
});

It is important to note that there is no need for a dataType property. Also, remove any random code like $( '#form' ).serialize(), as it is not valid syntax (expressions cannot be inserted into object literal expressions).

In PHP:

<?php

$_FILES['file1']['name'] === 'file1.pdf';
$_FILES['file2']['name'] === 'newFile2Name.pdf';

$_POST['username'] === "password"
$_POST['file_id'] === "4"

?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Simultaneous Checking of Two Checkboxes in a Single Row

I came across a similar question that was answered in this link. However, I am looking for a way to only check the checkbox next to another checkbox. Here's an example: +-------------------------------+ |column1 | column2 |column3 | +----------- ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error: express_1 | TypeError: Cannot read property ' ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

Utilizing Naive Bayes in Python, PHP, and JavaScript with Node.js

I am currently developing a data extraction algorithm specifically for group buying websites in order to create a deal aggregator. I already have algorithms in place for extracting images, discounts, and coordinates, but now I need a naive Bayes algorithm ...

What could be causing my table to not display?

I imported a CSV file with data on time, events, and location. The data was loaded into separate arrays for each column. I attempted to display the arrays as an HTML table using a for loop, but the table is not showing up. What could be causing this issue? ...

Step-by-step guide on how to include the "content-based-recommender" package in a Reactjs project

I recently started learning React.js and I'm interested in using the "Content-Based Recommender" package from npm. However, after downloading it, I encountered an issue with importing it. The documentation suggests the following: const ContentBasedRec ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

Getting a URL path in Next.js without relying on the Link component when the basePath is configured

Base Path from the next.js documentation states: For instance, by setting basePath to /docs, /about will automatically transform into /docs/about. export default function HomePage() { return ( <> <Link href="/about"> ...

The mysql database connection experiences failure after an ajax request is made

I've encountered an issue with a function that connects to MySQL DB. It works perfectly in a "normal" call, but fails to connect when triggered by an AJAX call. Here is the PHP code snippet: // Return data for ShowDdl() function getDDLdata($tabl ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Ajax transmitting data with concealed characters

I'm trying to send data from one PHP site to another. On the first site, everything looks good. The string appears as --show="author,book,text/n However, when I check the string after receiving it on the second site, it shows --show="author,b ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

Dealing with an overwhelming amount of logic in the controller compared to the models communicating with each other

While developing a small application, I ran into a code design dilemma. The application features multiple tables, each with 2 seats. Once two players sit at the same table, a game commences. In my current setup, I have a tables controller, a table model, ...

Avoid activating the panel by pressing the button on the expansion header

I'm facing a problem with the delete button on my expansion panel. Instead of just triggering a dialogue, clicking on the delete button also expands the panel. How can I prevent this from happening? https://i.stack.imgur.com/cc4G0.gif <v-expansion ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...