Solved

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

Posted on 2016-07-22
8
97 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
[X]
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
8 Comments
 
LVL 15

Expert Comment

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

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"
<?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 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 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.
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
Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

 
LVL 34

Expert Comment

by:Slick812
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>
<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
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 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
 */
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
ID: 41735129
Please excuse my behavior by not responding sooner.  This was because my daughter got married over the weekend.  I will respond shortly.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41735167
Congratulations!
0
 
LVL 110

Expert Comment

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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
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…

738 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