PHP

How to send Ajax request and get Ajax response in PHP

Ravindra Kumar

In this post I am going to tell how can we send ajax request in PHP and how can we get ajax response in PHP. In this example we shall create a form and this might have fields such as name, email, phone and message when this form submits the data will be set to PHP file and that PHP file will send a response of ajax with formatted message so following are the steps which required to make this program.

Step 1:

Need to create a form by which we can send ajax request to PHP file and this PHP file will return a response so following is the code of form.

<form action="#" class="form-group" autocomplete="off">
                        
                        <div class="form-group mb-3">
                            <input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
                        </div>
                        <div class="form-group mb-3">
                            <input type="email" name="email" class="form-control" id="email" placeholder="Email" required>
                        </div>
                        <div class="form-group mb-3">
                            <input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
                        </div>
                        
                        <div class="form-group mb-3">
                            <textarea name="message" id="message" cols="30" rows="5" class="form-control" placeholder="Message"></textarea>
                        </div>
                        <div class="text-end">
                            <button type="button" class="btn btn-primary" onclick="check();">Submit</button>
                         <div id="result" style="text-align:left;"></div>   
                        </div>
   </form>

In above form code there are few important stuff such as button and form, You need to give type of button as button so that javascript function can be called onclick event and in form action you don’t need to give any thing except #.

Step 2:

Now, need to create JavaScript script in which we can use AJAX as well so following is the code of javascript

<script>
       function check()
       {
           var name=document.getElementById("name").value;
           var email=document.getElementById("email").value;
           var phone=document.getElementById("phone").value;
           var message=document.getElementById("message").value;
           

           $.ajax({
            type: 'POST',
            url: 'pro.php',
            data: { name: name, email: email,phone: phone, message: message },
            success: function(response) {
                $('#result').html(response);
                
                if(response=='go')
                {
                    alert(response);
                
                }
                }
            });
       
           
       }
   </script>

By using document.getElementById("name").value;, I am using values of all fields of input.getElementById() function is used to get the value of particular input field but to get the value of a particular fiedl you need to specify that field’s id such as input type="text" id="name" .
After getting values of input fields i need to use $.ajax() and also need to pass data with post method.In the success: function(response) section we are receiving response if request is successful. By $('#result').html(response); , I am also printing the response sent by PHP file pro.php, We can also check the response as per condition such as if(response=='go').

Step 3:

Following is the PHP file called pro.php. This files is used to manage the request sent by ajax and this is also used to send response.

<?php

$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];

echo "<h4>Your Dertails !</h4>";
echo "<b>Name</b> : ".$name."<br/><b>E-mail</b> : ".$email."<br/><b>Phone</b> : ".$phone."<br/><b>Message</b> : ".$message;



?>

In above code we are getting data by using $_POST[] and by echo it is printing the message and this message will be passed as response to the ajax and this response will be printed on $('#result').html(response);.

Ravindra Kumar

Ravindra is a passionate full stack developer and dedicated blogger with a flair for crafting user-friendly web applications and insightful articles. With expertise spanning front-end and back-end technologies, Ravindra brings ideas to life through innovative coding solutions.

Suggested Reading

How to Create a Simple Login System in PHP

A login system is one of the most essential features of any website or web application. Whether it’s an e-commerce site, a blogging platform, or an internal company portal, user authentication ensures that only authorized users can access specific areas. In this article, we’ll walk through creating a simple login system in PHP using MySQL. […]

Clear Cache After Logout in PHP | Prevent going to back after logout in PHP

One of the most common issues developers face when building a login system in PHP is users being able to press the back button after logging out and still seeing the dashboard or other protected pages. This happens because browsers often cache pages, so even without an active session, the back button shows the previously […]

How to Create a PHP Registration Form with Gmail SMTP Email Confirmation

Building a secure and user-friendly registration system is one of the most common requirements in web development. In this tutorial, we’ll create a registration form in PHP that: Accepts username, email, and password Validates for unique username and email Stores passwords in a secure hashed format Sends a confirmation email using Gmail SMTP with PHPMailer […]

PHP Login Dashboard Template with Bootstrap Free Download

A secure and stylish login dashboard is one of the most essential components of any web application. Whether you’re building an admin panel, school management system, e-commerce backend, or a personal project, having a professional login system with a responsive dashboard can save you both time and effort. In this article, we’ll discuss how you […]

How to send emails by Gmail SMTP Emails in PHP

I’ll show you how to make this Bootstrap form send emails using SMTP. We’ll do this in PHP with PHPMailer, because: It’s reliable Supports SMTP authentication Works with Gmail, Outlook, and custom mail servers Install PHPMailer You can either: Via Composer (recommended) composer require phpmailer/phpmailer Or download from: PHPMailer GitHub and include it manually. HTML […]

How to Create Your Own CAPTCHA (Number Addition) with Form in PHP

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a simple security mechanism used to prevent automated bots from submitting forms on your website. While there are third-party CAPTCHA services like Google reCAPTCHA, creating a basic number-based CAPTCHA using PHP can be an effective and lightweight solution for small projects. In […]