SlideShare a Scribd company logo
Submit form with Ajax and
jQuery without reloading page
October 9, 2022 by Pawan
Table of Contents
● Introduction
● Powerful Combo of jQuery + Ajax
● UI Code of HTML Form
● The logic of Submitting Form without reload
● PHP Code to link Database
● Final process
● Conclusion
Introduction
Howdy friends, these days when people fill out a form on webpages they want
an instant response!
So today in this article, we will show you how to submit form with Ajax and
jQuery without reloading the page. Yup! your form will be submitted but the
webpage won’t refresh at all. To achieve this we will use our trusted jQuery
and Ajax.
But Ajax is the key here!
Because it allows us to send and receive data without refreshing our
webpage. Don’t worry I will explain it in detail in the next section.
You can use our code in combination with PHPMailer or Sendgrid to send
emails as well. And send emails without any refresh or reload. Meaning with
Ajax form submit without refresh, you can build applications where you can
submit the form and display the results on the same page.
Anyway, let’s learn the basics first of jQuery and Ajax.
Powerful Combo of jQuery + Ajax
Modern web development won’t exist without JavaScript. And jQuery is one of
the most used JS libraries you can think of in modern web development. But
ever since its release Ajax has joined its ranks because of vital things we can
do with Ajax.
Remember, Ajax also called Asynchronous JavaScript And XML is not a
framework or library, or even a language itself. Instead, Ajax is a web
development technique to send and receive data asynchronously. If want to
know more read this MDN article about Ajax.
How AJAX works behind the scene
Could we simply use Ajax without jQuery?
The answer is: YES! But no one does that unless you want to write verbose
Ajax submit form PHP code. jQuery makes writing Ajax simpler and more fun.
Now that we know why we are going to submit form with Ajax and jQuery
together. Let’s go into the coding section:
UI Code of HTML Form
First, we must design the UI. With Bootstrap handling CSS, we will design our
UI which look like this:
How UI should look for the jQuery submit form with Ajax
To build our UI, our main file is: “index.html“.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>jQuery submit form with Ajax</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootst
rap.min.css" rel="stylesheet">
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
</head>
<body>
<h3 class="py-2 text-center mb-4">jQuery Submit Form with
Ajax</h3>
<div class="container">
<div class="card mx-auto p-3" style="width: 20rem;">
<div class="card-body">
<form action="post.php" id="submitform" method="post">
<div class="input-group mb-4">
<span class="input-group-text"><i class="large
material-icons">account_circle</i></span>
<input type="text" class="form-control"
placeholder="Username" name="username">
</div>
<div class="input-group mb-4">
<span class="input-group-text"><i class="large
material-icons">email</i></span>
<input type="email" class="form-control"
placeholder="Email Address" name="email">
</div>
<div class="input-group mb-4">
<span class="input-group-text"><i class="large
material-icons">fingerprint</i></span>
<input type="password" class="form-control"
placeholder="Password" name="password">
</div>
<div class="text-center">
<button type="submit" class="btn btn-success"
name="submit">Submit</button>
</div>
</form>
</div>
<div class="result text-center"></div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstra
p.bundle.min.js"></script>
</body>
</html>
At this point in time, our UI will look like this for our jQuery Submit form with
Ajax. Next, we code the logic which makes our form gets submitted without
any reloading.
The logic of Submitting Form without
reload
As we explained at the start, Ajax is the main technique to send our data to
the server and receive data at the same time. Then we display this data at UI.
● We use the submit() jQuery function to submit our form. Though
we need to provide an id to identify our form.
● Next, we inject the event.preventDefault() function which
removes the default functionality of submit button click.
● jQuery Ajax function $.ajax() or jQuery.ajax() is the main
function which send or receive data. It has certain argument
requirements like
○ Type: post or get method
○ URL: Url of file such as in this case “post.php“
○ data: here we write code that processes the data we
receive from the form. In our jQuery submit form with
Ajax, we are utilizing serialize() jQuery to collect data
from the form.
$('#submitform').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "post.php",
data: $(this).serialize(),
success: function (data) {
console.log(data);
$('.result').html(data);
}
});
});
Now that we completed most of the code. Let’s move to the coding part where
we insert the data into the database.
PHP Code to link Database
For this form submission, we are collecting data and sending it to our MySQL
database. If you want to know how to build a simple DB read this.
To insert data into MySQL we use PHP as a backed powerhouse. For that
purpose, we have a simple PHP file: “post.php“.
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$connect = mysqli_connect('localhost', 'root', '', 'ajax_form');
$sql = "insert into form_data (username, email, password)
values('$username', '$email', '$password')";
if (mysqli_query($connect, $sql)) {
echo "Data Inserted Successfully!";
} else {
echo "Data failed to be inserted!";
}
Now that we are almost finished with UI and Logic part of our form. Let’s move
on to the SQL part.
Feel free to run the below code to build a quick SQL Table.
CREATE TABLE `form_data` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Below is the image of how your UI will look after we submit form without
reloading the page jQuery.
How jQuery submit form with ajax look
Final process
After filling out the form you can view your submitted data in the database.
Below is the image explaining how your database should look like for our Ajax
Submit form PHP.
Database for jQuery Submit Form with Ajax.
Feel free to download our code from GitHub Repo or check out the demo:
Code Download from Github Demo
Conclusion
We hope that you enjoyed our article on how to submit forms with Ajax and
jQuery. Feel free to comment on this article if you have any questions. Thank
you for reading, we are always excited when one of our posts is able to
provide useful information on a topic like this!
Also, check out our post about building a PHP shopping cart with the session,
and if you need a payment gateway then check out the Razorpay integration
guide.
Ta-da! Thanks for reading! Keep Coding.

More Related Content

Similar to Submit form with Ajax and jQuery without reloading page.pdf

jQuery
jQueryjQuery
jQueryi.omar
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
Appear
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
Katy Slemon
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Nagaraju Sangam
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
Erick Ranes Akbar Mawuntu
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
Clarence Ngoh
 
Ajax3
Ajax3Ajax3
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdfHow to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
Be Problem Solver
 
Lesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayLesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayCodecademy Ren
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Alex Chaffee
 
Boost your angular app with web workers
Boost your angular app with web workersBoost your angular app with web workers
Boost your angular app with web workers
Enrique Oriol Bermúdez
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
Katy Slemon
 
Loadrunner
LoadrunnerLoadrunner
Loadrunner
Kenneth Kufluk
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 

Similar to Submit form with Ajax and jQuery without reloading page.pdf (20)

jQuery
jQueryjQuery
jQuery
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
 
JavaScript Libraries
JavaScript LibrariesJavaScript Libraries
JavaScript Libraries
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
 
Ajax3
Ajax3Ajax3
Ajax3
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdfHow to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
How to develop an API with PHP, JSON, and POSTMAN in 9 Steps.pdf
 
Lesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ayLesson 202 02 oct13-1800-ay
Lesson 202 02 oct13-1800-ay
 
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnitWriting and Testing JavaScript-heavy Web 2.0 apps with JSUnit
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
 
Boost your angular app with web workers
Boost your angular app with web workersBoost your angular app with web workers
Boost your angular app with web workers
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
 
Loadrunner
LoadrunnerLoadrunner
Loadrunner
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 

Recently uploaded

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
QADay
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Submit form with Ajax and jQuery without reloading page.pdf

  • 1. Submit form with Ajax and jQuery without reloading page October 9, 2022 by Pawan Table of Contents ● Introduction ● Powerful Combo of jQuery + Ajax ● UI Code of HTML Form ● The logic of Submitting Form without reload ● PHP Code to link Database ● Final process ● Conclusion Introduction
  • 2. Howdy friends, these days when people fill out a form on webpages they want an instant response! So today in this article, we will show you how to submit form with Ajax and jQuery without reloading the page. Yup! your form will be submitted but the webpage won’t refresh at all. To achieve this we will use our trusted jQuery and Ajax. But Ajax is the key here! Because it allows us to send and receive data without refreshing our webpage. Don’t worry I will explain it in detail in the next section. You can use our code in combination with PHPMailer or Sendgrid to send emails as well. And send emails without any refresh or reload. Meaning with Ajax form submit without refresh, you can build applications where you can submit the form and display the results on the same page. Anyway, let’s learn the basics first of jQuery and Ajax. Powerful Combo of jQuery + Ajax Modern web development won’t exist without JavaScript. And jQuery is one of the most used JS libraries you can think of in modern web development. But ever since its release Ajax has joined its ranks because of vital things we can do with Ajax. Remember, Ajax also called Asynchronous JavaScript And XML is not a framework or library, or even a language itself. Instead, Ajax is a web development technique to send and receive data asynchronously. If want to know more read this MDN article about Ajax.
  • 3. How AJAX works behind the scene Could we simply use Ajax without jQuery? The answer is: YES! But no one does that unless you want to write verbose Ajax submit form PHP code. jQuery makes writing Ajax simpler and more fun. Now that we know why we are going to submit form with Ajax and jQuery together. Let’s go into the coding section: UI Code of HTML Form First, we must design the UI. With Bootstrap handling CSS, we will design our UI which look like this:
  • 4. How UI should look for the jQuery submit form with Ajax To build our UI, our main file is: “index.html“. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery submit form with Ajax</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootst rap.min.css" rel="stylesheet">
  • 5. <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <h3 class="py-2 text-center mb-4">jQuery Submit Form with Ajax</h3> <div class="container"> <div class="card mx-auto p-3" style="width: 20rem;"> <div class="card-body"> <form action="post.php" id="submitform" method="post"> <div class="input-group mb-4"> <span class="input-group-text"><i class="large material-icons">account_circle</i></span> <input type="text" class="form-control" placeholder="Username" name="username"> </div> <div class="input-group mb-4"> <span class="input-group-text"><i class="large material-icons">email</i></span>
  • 6. <input type="email" class="form-control" placeholder="Email Address" name="email"> </div> <div class="input-group mb-4"> <span class="input-group-text"><i class="large material-icons">fingerprint</i></span> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <div class="text-center"> <button type="submit" class="btn btn-success" name="submit">Submit</button> </div> </form> </div> <div class="result text-center"></div> </div> </div>
  • 7. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstra p.bundle.min.js"></script> </body> </html> At this point in time, our UI will look like this for our jQuery Submit form with Ajax. Next, we code the logic which makes our form gets submitted without any reloading. The logic of Submitting Form without reload As we explained at the start, Ajax is the main technique to send our data to the server and receive data at the same time. Then we display this data at UI. ● We use the submit() jQuery function to submit our form. Though we need to provide an id to identify our form. ● Next, we inject the event.preventDefault() function which removes the default functionality of submit button click. ● jQuery Ajax function $.ajax() or jQuery.ajax() is the main function which send or receive data. It has certain argument requirements like ○ Type: post or get method ○ URL: Url of file such as in this case “post.php“ ○ data: here we write code that processes the data we receive from the form. In our jQuery submit form with
  • 8. Ajax, we are utilizing serialize() jQuery to collect data from the form. $('#submitform').submit(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: "post.php", data: $(this).serialize(), success: function (data) { console.log(data); $('.result').html(data); } }); }); Now that we completed most of the code. Let’s move to the coding part where we insert the data into the database.
  • 9. PHP Code to link Database For this form submission, we are collecting data and sending it to our MySQL database. If you want to know how to build a simple DB read this. To insert data into MySQL we use PHP as a backed powerhouse. For that purpose, we have a simple PHP file: “post.php“. <?php $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $connect = mysqli_connect('localhost', 'root', '', 'ajax_form'); $sql = "insert into form_data (username, email, password) values('$username', '$email', '$password')"; if (mysqli_query($connect, $sql)) { echo "Data Inserted Successfully!"; } else { echo "Data failed to be inserted!"; }
  • 10. Now that we are almost finished with UI and Logic part of our form. Let’s move on to the SQL part. Feel free to run the below code to build a quick SQL Table. CREATE TABLE `form_data` ( `id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; Below is the image of how your UI will look after we submit form without reloading the page jQuery. How jQuery submit form with ajax look
  • 11. Final process After filling out the form you can view your submitted data in the database. Below is the image explaining how your database should look like for our Ajax Submit form PHP. Database for jQuery Submit Form with Ajax. Feel free to download our code from GitHub Repo or check out the demo: Code Download from Github Demo Conclusion We hope that you enjoyed our article on how to submit forms with Ajax and jQuery. Feel free to comment on this article if you have any questions. Thank you for reading, we are always excited when one of our posts is able to provide useful information on a topic like this!
  • 12. Also, check out our post about building a PHP shopping cart with the session, and if you need a payment gateway then check out the Razorpay integration guide. Ta-da! Thanks for reading! Keep Coding.