Ajax Form Submit examples using jQuery

Ajax Form Submit examples using jQuery

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.

Overview

In this jQuery Ajax submits a multipart form or FormData tutorial example – you will learn how to submit the form using the jquery ajax with multi-part data or FromData. Here you will know about the basic faqs of jquery ajax form.

In this tutorial, learn jquery ajax form submits with the form data step by step. A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax().

If you will be using jQuery’s Ajax Form Submit, you can send the form data to the server without reloading the entire page. This will update portions of a web page – without reloading the entire page.

AJAX: AJAX (asynchronous JavaScript and XML) is the art of exchanging data with a server and updating parts of a web page – without reloading the entire page.

Table Of Contents

  • Create HTML Form
  • jQuery Ajax Code

FAQs

  • How to add extra fields or data with Form data in jQuery ajax?
  • ajax FormData: Illegal invocation
  • How to send multipart/FormData or files with jQuery.ajax?

Create HTML Form

In this step, we will create an HTML form for multiple file uploads or FormData and an extra field.

<!DOCTYPE html>
<html>
<title>jQuery Ajax Form Submit with FormData Example</title>
<body>
 
<h1>jQuery Ajax Form Submit with FormData Example</h1>
 
<form method="POST" enctype="multipart/form-data" id="myform">
    <input type="text" name="title"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="submit" value="Submit" id="btnSubmit"/>
</form>
 
<h1>jQuery Ajax Post Form Result</h1>
 
<span id="output"></span>
 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> 
 
</body>
</html>

jQuery Ajax Code

In this step, we will write jquery ajax code for sending a form data to the server.

$(document).ready(function () {
 
    $("#btnSubmit").click(function (event) {
 
        //stop submit the form, we will post it manually.
        event.preventDefault();
 
        // Get form
        var form = $('#fileUploadForm')[0];
 
       // Create an FormData object 
        var data = new FormData(form);
 
       // If you want to add an extra field for the FormData
        data.append("CustomField", "This is some extra data, testing");
 
       // disabled the submit button
        $("#btnSubmit").prop("disabled", true);
 
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 800000,
            success: function (data) {
 
                $("#output").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
 
            },
            error: function (e) {
 
                $("#output").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
 
            }
        });
 
    });
 
});

FAQs – jQuery Ajax Form Submit

1. How to add extra fields with Form data in jQuery ajax?

The **append()** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

// Create an FormData object 
    var data = new FormData(form);
 
// If you want to add an extra field for the FormData
    data.append("CustomField", "This is some extra data, testing");

2. ajax FormData: Illegal invocation

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

processData: false,
contentType: false

3. How to send multipart/FormData or files with jQuery.ajax?

In this step you will learn how to send multiple files using jQuery ajax. Let’s see the below code Snippet:

var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});
 
$.ajax({
    url: 'upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(data){
      console.log('success');
    }
});

Note

Conclusion

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.

jQuery ajax get request method example

jQuery ajax get request method example

### jQuery Ajax Get Request Method Example This article is originally published at [https://www.tutsmake.com/jquery-api-ajax-get-method-example/](https://www.tutsmake.com/jquery-api-ajax-get-method-example/...

jQuery Ajax Get Request Method Example

This article is originally published at https://www.tutsmake.com/jquery-api-ajax-get-method-example/

Let's see example of jquery ajax get request.

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Ajax GET Request Example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
<style>  
.formClass
{
    padding: 15px;
    border: 12px solid #23384E;
    background: #28BAA2;
    margin-top: 10px;
} 
</style> 
<script type="text/javascript">
$(document).ready(function(){
   $("button").click(function(event){
 
    var name = "Tutsmake";
     
    $.get('https://www.tutsmake.com/Demos/html/ajax-get-method.php', {webname: name}, function(data){
 
        $("#output").html(data);
    });
 
  });
 
});
</script>
</head>
<body>
    <div class="formClass">
      <button type="button">Click &amp; Get Data</button><br>
      <div id="output">Hello</div>    
    </div>
</body>
</html>   ```                         

This article is originally published at [https://www.tutsmake.com/jquery-api-ajax-get-method-example/](https://www.tutsmake.com/jquery-api-ajax-get-method-example/ "https://www.tutsmake.com/jquery-api-ajax-get-method-example/")

How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

I’m going to share some tricks about XML file and APIs processing. I will also demonstrate how a web page can fetch information from an XML file in JavaScript using JQuery AJAX.

Assumptions: for the purpose of this article, I’m going to assume that you have good understanding and knowledge of JavaScript, the XML file format, and jQuery. If not please find documentation here to learn more details about it.

The project I worked on recently consisted of processing XML data resulting from an API call. The resulting **XML data **file was very large and its content is private data that I can’t share. *So in this post, I will show you how to process an ****XML demo ***file.

Below is the sample XML file from w3chools that I’ll be using for the demo:

<?xml version="1.0" encoding="UTF-8"?>
	

	<breakfast_menu> 
	   
	   <food> 
	       <name>Belgian Waffles</name> 
	       <price>$5.95</price> 
	       <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> 
	       <calories>650</calories> 
	   </food> 
	   
	   <food> 
	       <name>Strawberry Belgian Waffles</name> 
	       <price>$7.95</price> 
	       <description>Light Belgian waffles covered with strawberries and whipped cream</description> 
	       <calories>900</calories> 
	   </food> 
	   
	   <food> 
	       <name>Berry-Berry Belgian Waffles</name> 
	       <price>$8.95</price> 
	       <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 
	       <calories>900</calories> 
	   </food> 
	   
	   <food> 
	       <name>French Toast</name> 
	       <price>$4.50</price> 
	       <description>Thick slices made from our homemade sourdough bread</description> 
	       <calories>600</calories> 
	   </food> 
	   
	   <food> 
	       <name>Homestyle Breakfast</name> 
	       <price>$6.95</price> 
	       <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 
	       <calories>950</calories> 
	   </food> 
	   
	</breakfast_menu>

Now, create a folder for the demo project and save the demo.xml file in it. I named mine “XML-demo”. Inside your project folder, create a JavaScript file and HTML file that will display the data (index.html and main.js). I’m not using a separate CSS file for styling.

I recommend using Visual Studio Code IDE for this demo and in your VS Code install Live Server extension.
The following is a screenshot of my demo folder opened in VS code:

VS Code IDE Screenshot — shows files

Next step is adding your script and jquery-UI references in your index.html and define how you would like to display data. I’m simply displaying data in a “ul” element. Here’s how my index.html looks like:

<!DOCTYPE html>
	<html lang="en">
	

	    <head>
	        <meta charset="UTF-8">
	        <meta name="viewport" content="width=device-width, initial-scale=1.0">
	        <meta http-equiv="X-UA-Compatible" content="ie=edge">
	        <title>XML-Jquery</title>
	        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
	

	        <!-- **************************************************************************************** 
	        !   connect your main.js script to hmtl                                                     *
	        !   add version of jquery                                                                   *
	        ! *************************************************************************************** -->
	        <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
	        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
	

	        <!-- javascript reference -->
	        <script type="text/javascript" src="./main.js"></script>
	    </head>
	

	    <body>
	        <div class="container">
	            <div class="jumbotron" style="text-align: center;">
	                <h1 id="headerTitle">Food Menu List</h1>
	            </div>
	

	            <ul></ul>
	

	        </div>
	    </body>
	

	</html>
	

	<!-- ****************************************** END **********************

Reading XML

So the basic method for doing asynchronous calls in jQuery is the AJAX() function, documented here. That documentation has a lot going on but that should get you started and help you walk through my main.js script to understand how the XML file is processed through AJAX:

// Do some stuff when page hmtl page is launched
	$(document).ready(function () {
	

	    $("#headerTitle").hide(300).show(1500);
	    // calling show food menu function
	    showFoodMenu();
	    
	    // If you want to fetch data from the file 
	    // call fetch data function instead of showFoodMenu
	    // fetchData()
	});
	

	// ***************************************************************************************
	// this function calls showfoodmenu 3000 milisecond to get new changes                   *
	// made on demo.xml                                                                      *
	// ***************************************************************************************
	function fetchData() {
	    setTimeout(function () {
	        showFoodMenu();
	        // recursive call
	        fetchData();
	    }, 3000);
	}
	

	// **************************************************************************************
	// read data from demo.xml using Jquery | AJAX                                          *
	// **************************************************************************************
	function showFoodMenu() {
	

	    $.ajax({
	        type: "GET",
	        url: "./demo.xml",
	        dataType: "xml",
	

	        error: function (e) {
	            alert("An error occurred while processing XML file");
	            console.log("XML reading Failed: ", e);
	        },
	

	        success: function (response) {
	

	            // make sure the ul is empty
	            // before appending data inot it
	            $("ul").children().remove();
	

	            $(response).find("food").each(function () {
	                var _name = 'Name: ' + $(this).find('name').text();
	                console.log(_name);
	                
	                var _price = 'Price: ' + $(this).find('price').text();
	                var _calories = 'Calories: ' + $(this).find('calories').text();
	                var _description = 'Description: ' + $(this).find('description').text();
	

	                // add content to the HTML          
	                $("ul").append('<li>' + _name + '</li>');
	                $("ul").append('<li>' + _price + '</li>');
	                $("ul").append('<li>' + _calories + '</li>');
	                $("ul").append('<li>' + _description + '</li>');
	            });
	        }
	    });
     }

You should have the icon for Go live on your VScode IDE if you successfully install [***Live Server***](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer "***Live Server***") extension. Clicked to Go Live icon on the right bottom of your VS code IDE or simply right click on HTML file and select “open with Live Server”. if you followed exactly and correctly what I did, you should get this:

Final result — Displaying XML data on HTML

Tips

Do not put the script reference to jquery-UI before the jquery script itself on your HTML otherwise you’ll get this error: ***Uncaught ReferenceError: $ is not defined. ***Make sure your script is referenced after you have referenced jquery-UI as I did in my main.js script.

Frequently used acronyms* API: Application programming interface

  • Ajax: Asynchronous JavaScript
  • CSS: Cascading Stylesheets
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • RSS: Really Simple Syndication
  • SGML: Standard Generalized Markup Language
  • SVG: Scalable Vector Graphics
  • URI: Uniform Resource Identifier
  • URL: Uniform Resource Locator
  • W3C: World Wide Web Consortium
  • XHTML: Extensible Hypertext Markup Language

If you enjoyed this story, you might also like “How to Set Up the Development Environment

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

There are two functions to deal with an array on the client-side – JavaScript's .forEach() and jQuery's .each(). Here, I will teach you how to use both of these methods with some sample code.

Your knowledge of JavaScript and jQuery is incomplete if you don't know how to loop with .forEach() and .each() methods. This tutorial helps you to quickly master JavaScript .forEach() & jQuery .each() in 2 minute time.

There are two methods to deal with an array on client-side – JavaScript .forEach() and jQuery .each(). Here, I will teach you how to use both of these methods in different scenarios.

Defination of these 2 methods

a. JavaScript .forEach() Method

The .forEach() method of JavaScript executes a given function once for each element of the array.

For example -

var arr = ['a', 'b', 'c'];    
arr.forEach(function(element) {  
    console.log(element);  
});  

The above JavaScript code will print – ‘a’, ‘b’, & ‘c’ in the console window.

b. jQuery .each() Method

jQuery has it’s own method called jQuery Each method and it is used to loop over arrays, array of object and matched elements of the DOM. See the below code:

var arr = ['a', 'b', 'c'];  
$.each(arr , function (index, value){  
  console.log(arr);   
});  

The above jQuery code will print – ‘a’, ‘b’, & ‘c’ in the console window.

Looping through DOM elements

a. JavaScript .forEach() Method

Suppose you want to extract all the anchor tags from the web page, and then loop through each of them. In that case first you have to get all the anchors using document.getElementsByTagName("a") and then convert it into an array. This is because JavaScript .forEach() method loops only through an array.

See the below code:

var links = document.getElementsByTagName("a");    
var Arr = Array.from(links);    
Arr.forEach(someFunction);    
    
function someFunction(currentValue) {    
    console.log(currentValue);    
}    

I used Array.from() method to convert to an array.

b. jQuery .each() Method

In case of .each() method you simply loop through all the anchor tags, like shown in the below code, as jQuery Each method can loop through arrays, array of objects and matched element of the DOM. So you don’t have to do the conversion to an array like JavaScript .forEach() method.

See the below code:

$("a").each(function (index, value) {   
  console.log($(this).attr("href"));   
});  

Clearly you can see in this case the lines of codes are very less than compared to .forEach() method of JavaScript.

Which one you should choose?

Case 1: DOM Manipulations

When working with DOM elements the jQuery Each method has a great advantage because it removes a lot of code lines. So prefer this method during DOM manipulations.

Case 2: Website is using jQuery from before

If your website is already using jQuery then you should use jQuery Each method because this will bring code consistency in your project.

In all other cases use JavaScript .forEach() method.

Conclusion

Both of these above methods are very good and they make the codes easy to understand. I would recommend every web developer to know both of these methods.

Thank you for reading.