Dynamically load content in Bootstrap Modal with AJAX

Bootstrap Modal Form Submit with jQuery & PHP

In our previous tutorial, you have learned how to Upload Multiple Image with jQuery, PHP & MySQL. In this tutorial you will learn how to implement Bootstrap modal form submit with jQuery and PHP.

Modal or dialog play an important role in any web application. The modals allow to handle additional functionality on same page without using any extra space space.

The Bootstrap modals are very user friendly and easy to integrate. The modals can be used for different requirement like showing any specific details on same page or handling form submit to process user input.

So if you’re looking for solution to implement Bootstrap modal with form submit to process form values, then you’re here at right place. In this tutorial you will learn how to show Bootstrap form with input and handle Bootstrap form submit with jQuery and process form submit post values at server in PHP.

The tutorial explained in easy steps with live demo of Bootstrap form with submit functionality and link to download source code of live demo.

So let’s start the coding, we will have following file structure for the example to handle Bootstrap Form submit with jQuery .

Читайте также:  Интересные приложения на java

Step1: Include Bootstrap and jQuery Files
First we will include Bootstrap and jQuery library files in head tag in index.php file. We will also include contact.js file in which handle form submit using jQuery.

Step2: Design Bootstrap Contact Form
In index.php file, we will design Bootstrap contact form with input fields and submit button. The modal will be opened when click on show contact form button.

×

Contact Form

Step3: Handle Bootstrap Contact Form Submit
In contact.js file, we will handle form submit jQuery .submit() function with return false to not submit directly to action. We will handle form submit values using Ajax by calling function submitForm() .

In function submitForm() , we will make Ajax request to saveContact.php with form submit values to process form values at server end.

function submitForm()< $.ajax(< type: "POST", url: "saveContact.php", cache:false, data: $('form#contactForm').serialize(), success: function(response)< $("#contact").html(response) $("#contact-modal").modal('hide'); >, error: function() < alert("Error"); >>); >

Step4: Process Contact Form Submit Values at Server End
Now finally in saveContact.php file, we will process form submitted $_POST values.

You may also like:

  • User Management System with PHP & MySQL
  • Datatables Add Edit Delete with Ajax, PHP & MySQL
  • Build Helpdesk System with jQuery, PHP & MySQL
  • Build Online Voting System with PHP & MySQL
  • School Management System with PHP & MySQL
  • DataTables Add Edit Delete with CodeIgniter
  • Create RESTful API using CodeIgniter
  • Build Reusable Captcha Script with PHP
  • Product Search Filtering using Ajax, PHP & MySQL
  • Image Upload and Crop in Modal with jQuery, PHP & MySQL
  • Build Push Notification System with PHP & MySQL
  • Project Management System with PHP and MySQL
  • Hospital Management System with PHP & MySQL
  • Build Newsletter System with PHP and MySQL
  • Skeleton Screen Loading Effect with Ajax and PHP
  • Build Discussion Forum with PHP and MySQL
  • Customer Relationship Management (CRM) System with PHP & MySQL
  • Online Exam System with PHP & MySQL
  • Expense Management System with PHP & MySQL

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

Источник

Dynamically load content in Bootstrap Modal with AJAX

Modals are one of the many pre-built components offered by the widely used front-end web development framework Bootstrap. Developers can display content on top of an existing page by using dialogue boxes or pop-up windows known as modals.

However, there are times when need to dynamically load content into the Modal, which is possible with AJAX.

AJAX allows data to be loaded and displayed on a page without having to reload the entire page, making the web application faster and more user-friendly.

In this tutorial, I will show you how to dynamically load MySQL database content into a Bootstrap Modal using AJAX and PHP.

I am using Bootstrap 5 in the example, if you are using any other version then also you can follow.

Dynamically load content in Bootstrap Modal with AJAX

Contents

1. Table structure

CREATE TABLE `employee` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `emp_name` varchar(100) NOT NULL, `salary` varchar(50) NOT NULL, `gender` varchar(10) NOT NULL, `city` varchar(80) NOT NULL, `email` varchar(100) NOT NULL );

2. Configuration

Create a config.php for the database connection.

Completed Code

4. AJAX – Return Bootstrap Modal Data

Read POST userid value and assign it to $userid variable. Select a record from employee table where id=$userid . Read the fetched data and create a table layout and assign it to $response variable.

Completed Code

 $sql = "select * from employee where = mysqli_query($con,$sql); $response = ""; while( $row = mysqli_fetch_array($result) )< $id = $row['id']; $emp_name = $row['emp_name']; $salary = $row['salary']; $gender = $row['gender']; $city = $row['city']; $email = $row['email']; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; $response .= ""; > $response .= "
Name : ".$emp_name."
Salary : ".$salary."
Gender : ".$gender."
City : ".$city."
Email : ".$email."
"; echo $response; exit;

5. jQuery – Send AJAX request to Dynamically Load Content

Define click event on userinfo class. Read data-id attribute value and assign it to userid variable.

Send AJAX POST request to ajaxfile.php file. Here, pass as data. On successful callback append response in .modal-body and display the modal calling show method.

Completed Code

$(document).ready(function()< $('.userinfo').click(function()< var userid = $(this).data('id'); // AJAX request $.ajax(< url: 'ajaxfile.php', type: 'post', data: , success: function(response) < // Add response in Modal body $('.modal-body').html(response); // Display Modal $('#empModal').modal('show'); >>); >); >);

6. Demo

7. Conclusion

Use AJAX when you want to use a single Bootstrap Modal to display information according to various requests otherwise, you can simply create multiple Modal with information for each task.

If you found this tutorial helpful then don’t forget to share.

Источник

Edit or Update Data with Bootstrap Modal in PHP & MySQL Using Ajax

In this code, we will show you how to display the data with Bootstrap Modal and Update it in PHP & MySQL using AJAX. This function is one of the most important functions when creating an application. So we hope that you found it helpful to your research.

Showing records to your Bootstrap modal with PHP is helping the user experience for not loading your web page.

Edit or Update Data in PHP & MySQL Using Ajax

Index.html

First, we need to create our index.html just check the below code.

         


Edit or Update Data Using PHP & MySQL Ajax



Add New Employee

List of Employees

Edit Employee

Save.php

After the above code so we need the save function so that we can enable us to add a new record.

connect_errno) < echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); > // Set the INSERT SQL data $sql = "INSERT INTO employees (email, first_name, last_name, address) VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')"; // Process the query so that we will save the date of birth if ($mysqli->query($sql)) < echo "Employee has been successfully created."; >else < return "Error: " . $sql . "
" . $mysqli->error; > // Close the connection after using it $mysqli->close(); ?>

All.php

Our next code is about getting all records via ajax.

connect_errno) < echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); > // Set the INSERT SQL data $sql = "SELECT * FROM employees"; // Process the query so that we will save the date of birth $results = $mysqli->query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $mysqli->close(); echo json_encode($row); ?>

Get.php

In this code, we will get the record and display it via modal.

connect_errno) < echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); > // Set the INSERT SQL data $sql = "SELECT * FROM employees WHERE "; // Process the query so that we will save the date of birth $results = $mysqli->query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $mysqli->close(); echo json_encode($row); ?>

Update.php

Now in this code, we are enabled to update the record after clicking the «Update» button via modal using ajax.

connect_errno) < echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); > // Set the INSERT SQL data $sql = "UPDATE employees SET email='".$email."', first_name='".$first_name."', last_name='".$last_name."', address='".$address."' WHERE "; // Process the query so that we will save the date of birth if ($mysqli->query($sql)) < echo "Employee has been sucessfully updated."; >else < return "Error: " . $sql . "
" . $mysqli->error; > // Close the connection after using it $mysqli->close(); ?>

Scripts.js

In this code, we are enabled to process the above PHP codes via AJAX from saving record, getting all records, retrieving records, and updating it.

 function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); > function save() < $("#btnSubmit").on("click", function() < var $this = $(this); //submit button selector using ID var $caption = $this.html();// We store the html content of the submit button var form = "#form"; //defined the #form ID var formData = $(form).serializeArray(); //serialize the form into array var route = $(form).attr('action'); //get the route using attribute action // Ajax config $.ajax(< type: "POST", //we are using POST method to submit the data to the server side url: route, // get the route value data: formData, // our serialized array data for server side beforeSend: function () , success: function (response) , error: function (XMLHttpRequest, textStatus, errorThrown) < // You can put something here if there is an error from submitted request >>); >); > function resetForm(selector) < $(selector)[0].reset(); >function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); > function update() < $("#btnUpdateSubmit").on("click", function() < var $this = $(this); //submit button selector using ID var $caption = $this.html();// We store the html content of the submit button var form = "#edit-form"; //defined the #form ID var formData = $(form).serializeArray(); //serialize the form into array var route = $(form).attr('action'); //get the route using attribute action // Ajax config $.ajax(< type: "POST", //we are using POST method to submit the data to the server side url: route, // get the route value data: formData, // our serialized array data for server side beforeSend: function () , success: function (response) , error: function (XMLHttpRequest, textStatus, errorThrown) < // You can put something here if there is an error from submitted request >>); >); > $(document).ready(function() < // Get all employee records all(); // Submit form using AJAX To Save Data save(); // Get the data and view to modal get(); // Updating the data update(); >);

Styles.css

Then our last code about the custom style of our page.

Okay, we were done setting up our code and you can now enable to update/edit your record using ajax. I hope this code can help you.

Источник

Оцените статью