How to Populate the SAME Html Form using php, js, jquery, and ajax Without Refreshing the Screen

Posted on 2016-07-22
Medium Priority
Last Modified: 2016-08-22
I have a simple form for a club that I have created containing 4 fields at http://members.vanhosting.cloud/test.php.  The form opens blank.  When the submit button is clicked, it should go to the actionTest.php and populate (fill) the fields of the same form without refreshing the screen and changing the structure in anyway.  It should also stay on the same test.php form but call the routine on the background.  

The problem is that it is going to the actionTest.php and the structure is changing.

How can I get it to populate (fill) the fields of the same form?
Question by:vanavah
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 15

Expert Comment

ID: 41725584
It has to be done via ajax method.
You have used plain php form . So how you expect that it would work as you wish.

will help you to get reference
LVL 111

Expert Comment

by:Ray Paseur
ID: 41725770
It's helpful to post your code samples in the CODE snippet so we can all see them inline, instead of having to open separate attachments.

Here is "test.php"

$email 		= "";  // set $email
$surname 	= "";  // set $surname 
$firstname 	= "";  // set $firstname 
$middlename = "";  // set $middlename


<form action="actionTest.php" method="post">
  <label>Email</label> <input name="email" value="<?php echo $email;?>">
  <label>Surname</label> <input name="surname" value="<?php echo $surname;?>">
  <label>First Name</label> <input name="firstname" value="<?php echo $firstname;?>">
  <label>Middle Name</label> <input name="Middle" value="<?php echo $middlename;?>">
   <button type="submit">Submit</button>


Open in new window

Here is "actionTest.php"

$email 		= "";  // set $email
$surname 	= "";  // set $surname 
$firstname 	= "";  // set $firstname 
$middlename = "";  // set $middlename

if (isset($_POST["email"])){
    $email 		= $_POST["email"]; // set $email to posted field named email
    $surname 		= $_POST["surname"]; // set $surname to posted field named surname
    $firstname 	= $_POST["firstname"]; // set $firstname to posted field named firstname
    $middlename 	= $_POST["middlename"]; // set $middlename to posted field named middlename
	$surname = "Brown";
	$firstname = "John";
	$middlename = "Ossie-Moore";


<form action="" method="post">
	<input name="email" value="<?php echo $email;?>">
	<input name="surname" value="<?php echo $surname;?>">
	<input name="firstname" value="<?php echo $firstname;?>">
	<input name="Middle" value="<?php echo $middlename;?>">

Open in new window

LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 total points (awarded by participants)
ID: 41725779
It looks like you need to get a foundation in how web applications work.  Hopefully these links can help you get that knowledge.

Client-Server protocols are the underpinning of all WWW applications.  This is key to understanding how AJAX requests work.

jQuery is one of the easiest ways to make a request without the appearance of a page load.  This article shows the essential moving parts.  The "success" function can update the form fields via jQuery.  jQuery uses selectors to locate "id" attributes and can get / set the contents of the selected page elements.

If you're new to PHP, please take a little time to learn the way PHP works.  You can skip over the parts you already know, but it's worth getting a foundation in the syntax and basic design patterns.

As time permits. I'll try to set up a code example that shows you how this sort of thing might be done.  I'll post back later after I've had a chance to write and test the code.
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

LVL 34

Expert Comment

ID: 41726007
greetings vanavah, , I did some code to do as you said, to use the actionTest.php to ajax Without Refreshing the Screen. But It was not as easy as I thought it would be.

this is the code for an .html web page. There is NO PHP in it, as it is not needed as far as I can see -
<!doctype html>
<html><head><title>JQuery AJAX Form Submit</title>

margin:2px auto;
border:3px solid #5ad;

#form1 label{
font-weight: bold;
color: #811;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script>  // I use 2.2.4 of Jquery

$(function() {
  $("#form1").submit(function(e) {
  var ajxSend = {
    type: "POST",
    url: "actionTest.php",
    data: $(this).serialize(),
    dataType: "json",
    timeout: 3500
  var aj = $.ajax(ajxSend);
  aj.done(function( received ) {
// IMPORTANT, you need to understand what should be SENT and RECEIVED by ajax
    if(received.error) { // test for error response
    alert("ERROR="+received.error+"- php value check Invlaid, "+received.message);
    return; // end ALL JS code

  $.each( received, function(key, val) {
    $( "input[name='"+key+"']" ).val(val);
  $("#title1").html("AJAX SUCCESS as SUBMIT for email= "+received.email);

  aj.fail(function(xhr, error1, err) {// the Status IS NOT a Number, but the Type of jquery ERROR
  if (xhr.status==404) alert("ERROR from Ajax as '404 status' the "+ajxSend.url+" page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!");
  else {
  alert("Ajax ERROR = \""+error1+"\", with server Status: "+xhr.status+", post-URL: "+ajxSend.url+", \npost-Data: "+ajxSend.data+", \nerror because: "+err);
  if (aj.responseText) {
    console.log("AJAX TEXT= "+aj.responseText);
    } else console.log("NO AJAX TEXT RECEIVED");

<body><h3 id="title1" style="text-align:center;">JQuery AJAX Form Submit</h3>

<form id="form1" action="actionTest.php" method="post">
  <label>Email</label> <input name="email" value="">
  <label>Surname</label> <input name="surname" value="">
  <label>First Name</label> <input name="firstname" value="">
  <label>Middle Name</label> <input name="Middle" value="">
   <button type="submit">Submit</button>



Open in new window

next is the code in the actionTest.php page
ini_set('display_errors', 1);
header('Cache-Control: no-cache');
// Change the Type to text/plain
header('Content-Type: text/plain');

if (count($_POST) < 1) {
  echo json_encode( array('error' => 'NO POST', 'message' => 'ERROR: The POST array was EMPTY') );

$errorMsg = '';
$outArray = array();
foreach($_POST as $key => $val) {
if (!$val) {
  $errorMsg .= $key.' needs to be filled, ';
$outArray[$key] = $val;

if ($errorMsg) {
  $outArray =  array('error' => 'EMPTY FIELDS', 'message' => $errorMsg);
  } else { // change the fields
  $outArray['surname'] .= " Brown";
  $outArray['firstname'] .= " John";
  $outArray['Middle'] .= " Ossie-Moore";

echo json_encode($outArray);

Open in new window

There to much there for me to try and explain all of what I did, In the .html page I use the JQuery  $.ajax( ) to send the <form> input values to the actionTest.php  page. . I really could not understand what you were doing in your actionTest.php code, you seemed to want to change the person's name inputs, , but I do not know why you do this? ?

This code works for me,

 so ask questions if you need explanations for how this may do it's work.
LVL 111

Accepted Solution

Ray Paseur earned 2000 total points (awarded by participants)
ID: 41728421
Here is an example that should help illuminate some of the important principles.  Since this is a two-part application we will need to look at the client / server scripts separately to see how they interact.  First, let's look at the server-side script.  It's pretty simple.  It expects a GET-method request and returns a JSON response.  The request will contain two fields named "dyn" and "stat."  The response object will return two fields named "dyn" and "stat."  The script will put the current timestamp into they dynamic field ("dyn") and will simply copy whatever was in the request["stat"] into the response->stat element.
<?php // demo/temp_vanavah_server.php
 * https://www.experts-exchange.com/questions/28959110/How-to-Populate-the-SAME-Html-Form-using-php-js-jquery-and-ajax-Without-Refreshing-the-Screen.html

$response = new StdClass;

$response->dyn = time();

$response->stat = $_GET['stat'];

echo json_encode($response);

Open in new window

Next let's look at the client-side of the process.  When the #clickable element is clicked, our function will create two variables, "ddata" and "sdata."  These variables will contain the values of the input controls from "#dynamic" and "#static" respectively.  We will use these values to create a GET request, passing the values as arguments.  When the server-side script responds to the request, we will receive a JSON string in the "response" variable.  We then use JSON.parse() to enable our JavaScript to extract the components from the response.  We assign these string values to the appropriate elements in the HTML.
<!DOCTYPE html>
<!-- https://www.experts-exchange.com/questions/28959110/How-to-Populate-the-SAME-Html-Form-using-php-js-jquery-and-ajax-Without-Refreshing-the-Screen.html -->
<html dir="ltr" lang="en-US">
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
#clickable {

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
        var ddata = $("#dynamic").val();
        var sdata = $("#static").val();
        $.get("temp_vanavah_server.php", {dyn:ddata,stat:sdata}, function(response){
            var resp = JSON.parse(response);

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<input id="dynamic"   name="dyn"  value="Dynamic Field" /><br>
<input id="static"    name="stat" value="Static Field" /><br>
<input id="clickable"             value="Fill in some form data and click here" />


Open in new window


Author Comment

ID: 41735129
Please excuse my behavior by not responding sooner.  This was because my daughter got married over the weekend.  I will respond shortly.
LVL 111

Expert Comment

by:Ray Paseur
ID: 41735167
LVL 111

Expert Comment

by:Ray Paseur
ID: 41759068
E-E sent me an email message asking me to close this question.

Featured Post

Interactive Way of Training for the AWS CSA Exam

An interactive way of learning that will help you visualize core concepts so that you can be more effective when taking your AWS certification exam.  Built for students by a student to help them understand the concepts that they are being taught.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question