Here is the php code I want to show if domain is available or not in same page without refresh
<form id="" method="post" class="cont"> <input type="text" name="domain_name" class="srchFld" placeholder=""/> <select class="tldFld" name="suffix"> <option value=".com">.com</option> <option value=".net">.net</option> <option value=".org">.org</option> <option value=".biz">.biz</option> <option value=".info">.info</option> <option value=".dz">.dz</option> </select> <div align="center"><button type="submit" name="check" class="srchBtn" id="loadbasic">Search</button></div> </form> <?php if(isset($_POST['check'])) { if (!empty($_POST['domain_name'])){ $name_domain = trim($_POST['domain_name']).$_POST['suffix']; $response = @dns_get_record($name_domain, DNS_ALL); if(empty($response)){ echo "<H2 style='color:green;' >Domain $name_domain is available.</H2>"; }else{ echo "<H2 style='color:red;'>Domain $name_domain has taken.</H2>"; } } else { echo "<H2 style='color:red;'>Error: Domain name can not be left empty.</H2>"; } } ?>
when this code runs, it refreshes same page and shows if the domain is working or not while what I want is to load everything in the same page Thanks in advance for your help
Advertisement
Answer
Just to add to what David said, you’ll need Ajax. So first you might want to take out the PHP code into a new file called processForm.php
, then set the action attribute on the form to action="processForm.php"
, then add the Jquery CDN library to the form page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
.
Here’s a code snippet, just add this after the jquery library CDN
<script> $(function() { // Get the form. var form = $('#domain-form'); // Set up an event listener for the domain form. $(form).submit(function(event) { // Stop the browser from submitting the form so as to avoid page refresh event.preventDefault(); var formData = $(form).serializeArray(); var paramObj = {}; $.each(formData, function(_, kv) { paramObj[kv.name] = kv.value; }); var domainName = $(form).find('input[name="domain_name"]').val(); if(domainName.length === 0) { form.prepend("<H2 style='color:red;'>Error: Domain name can not be left empty</H2>"); return false; } // Submit the form using AJAX. $.ajax({ type: 'POST', url: $(form).attr('action'), data: paramObj, // The data sent to the server dataType: 'json' // The data type expected of the server response. success: function(response) { if(response) { form.prepend("<H2 style='color:red;'>Domain " + domainName + " has taken.</H2>") } else { form.prepend("<H2 style='color:red;'>Domain " + domainName + " is available.</H2>") } }) }); }); </script>
The PHP could look like this
<?php if(isset($_POST['check'])) { if ($_POST['domain_name']){ $name_domain = trim($_POST['domain_name']).$_POST['suffix']; $response = @dns_get_record($name_domain, DNS_ALL); echo json_encode($response); } }