Solved

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

Posted on 2016-07-22
8
62 Views
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?
test.php
actionTest.php
0
Comment
Question by:vanavah
8 Comments
 
LVL 15

Expert Comment

by:Insoftservice
Comment Utility
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
https://www.formget.com/submit-form-using-ajax-php-and-jquery/
1
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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"
<?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;?>">
  <br><br>
  <label>First Name</label> <input name="firstname" value="<?php echo $firstname;?>">
  <br><br>
  <label>Middle Name</label> <input name="Middle" value="<?php echo $middlename;?>">
  <br><br>
  
   <button type="submit">Submit</button>

</form>

Open in new window

Here is "actionTest.php"
<?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;?>">
</form>

Open in new window

1
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points (awarded by participants)
Comment Utility
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.
https://www.experts-exchange.com/articles/11271/Understanding-Client-Server-Protocols-and-Web-Applications.html

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.
https://www.experts-exchange.com/articles/10712/The-Hello-World-Exercise-with-jQuery-and-PHP.html

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.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

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.
1
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
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>
<style>
body{background:#e3f7ff;}

#form1{
width:25em;
min-height:4em;
background:#fbdba0;
margin:2px auto;
border:3px solid #5ad;
padding:9px;
}

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

</style>
<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) {
    e.preventDefault();
	
  var ajxSend = {
    type: "POST",
    url: "actionTest.php",
    data: $(this).serialize(),
    dataType: "json",
    timeout: 3500
    }
alert	
  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");
  }
  });
	
  });
});

</script>
</head>
<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="">
  <br><br>
  <label>Surname</label> <input name="surname" value="">
  <br><br>
  <label>First Name</label> <input name="firstname" value="">
  <br><br>
  <label>Middle Name</label> <input name="Middle" value="">
  <br><br>
  
   <button type="submit">Submit</button>

</form>

</body>
</html>

Open in new window


next is the code in the actionTest.php page
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
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') );
  exit();
  }

$errorMsg = '';
$outArray = array();
foreach($_POST as $key => $val) {
if (!$val) {
  $errorMsg .= $key.' needs to be filled, ';
  continue;
  }
$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.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points (awarded by participants)
Comment Utility
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
 */
error_reporting(E_ALL);


// A RESPONSE OBJECT
$response = new StdClass;

// PUT THE CURRENT TIMESTAMP INTO THE DYNAMIC FIELD
$response->dyn = time();

// PUT THE UNCHANGED REQUEST VARIABLE INTO THE STATIC FIELD
$response->stat = $_GET['stat'];

// RETURN THE RESPONSE OBJECT
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">
<head>
<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 {
    color:white;
    background-color:navy;
    width:16em;
}
/* STYLE SHEET HERE */
</style>

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

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

<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" />

</body>
</html>

Open in new window

0
 

Author Comment

by:vanavah
Comment Utility
Please excuse my behavior by not responding sooner.  This was because my daughter got married over the weekend.  I will respond shortly.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Congratulations!
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
E-E sent me an email message asking me to close this question.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now