Jump to content

process form data without reloading the page


Balderick
 Share

Recommended Posts

 

Hello,

I have a question about how to send form data to the database, without reloading the entire page.

I discovered working with xmlhttprequest. I managed to show text from another file by implementing a javascript function with xhr into my script.

I don’t know much about javascript and don’t understand how a javascript form should be added to an existing function.

Finally this should run a php script executing the code to add the form data to the database.

 

	<!DOCTYPE html>
	<html>
	<body bgcolor="grey">
	<center>
			<br><br><br>

	 
	<div style="height: 200px; width: 600px; border: solid 2px blue;">

	<div id="kn_ze">
	 <form id="my_form" action="">
	Give your name: <input type="text" name="fname">
	<br>
	<input type="submit" value="Send" onclick="loadXMLDoc();">
	<!--
	<button type="button" onclick="loadXMLDoc()">send it</button>
	-->

	</form>

	 
	</div>
	 </div>
	 
	 
	 
	 
	 
	<script>
	function loadXMLDoc() {
		
	/*	 document.getElementById("my_form").submit();*/
		 
		 
		 
	  var xhttp = new XMLHttpRequest();
	  xhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
		  document.getElementById("kn_ze").innerHTML = this.responseText;
		  
		  
		}
	  };
	  xhttp.open("GET", "prophp.php", true);
	  xhttp.send();
	}
	</script>

	</body>
	</html>

 

 

test script to process the form data

 

prophp.php :

	<?php 


	echo '<br>test code here : ';

	if (isset($_POST['fname']))
	{
		
		var_dump($_POST['fname']);
		
		// execute mysql queries
	}

	?>

 

 

11)      How are the form data placed in the existing function? (or should I create a second one? )

Maybe someone can help me out solving it.

Link to comment
Share on other sites

Unfortunately, W3Schools does not have any examples of POST requests.

Here's an example of sending form data upon submission:

// Add a submit event handler to the form
var form = document.getElementById("my_form");
form.addEventListener("submit", submitForm, false);

function submitForm(e) {
  // Cancel form submission
  e.preventDefault();

  // Build a query string from the form data
  var form = e.currentTarget;
  var query = "", element;
  for(var i = 0; i < form.elements.length; i++ ) {
    element = form.elements[i];
    if(element.name) {
      query += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value);
      query += "&";
    }
  }

  // Send a request
  var request = new XMLHttpRequest();
  request.onreadystatechange = doSomething;
  request.open("POST", "file.php", true);
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(query); // Form data is here

  // Handle response here however you want to
  function doSomething() {
    if(request.readyState == 4) {
      if(request.status == 200) {
        // Success
        //
        //
      } else {
        // Error
        //
        //
      }
    }
  }
}

 

Link to comment
Share on other sites

 

Thank you for the answer.

Like I said I have not much experience with javascript and I have a lot of questions.

With a lot I mean A LOT. I counted 10,  so be prepared.:D

I still gonna ask them, I hope your explanation clears a lot.

-          Which events have which sequence? (in response to: e.PreventDefault)

-          What is the use of e.CurrentTarget?

-          With which reason is the query variable made?

-          Is EncodeURIComponent a way of sanitizing/validation?

o   Is it (EncodeURIComponent) obliged (strongly recommended) in javascript or is SSL enough in most cases?

-          Which safety aspects should I heed at when making ajax forms?

o   Are these security aspect different from php?

o   With which reason is php sufficient or not?

-          Can you embed a javascript function inside a function?

o   How does html process this?

Link to comment
Share on other sites

e.preventDefault() stops the form from submitting which would reload the page. e.currentTarget points to the form itself, which is the element that fired the submission event.

You need to understand Javascript events. Here's the description of addEventListener() and the use of the currentTarget property of the event object:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

I'm amazed there isn't a proper simple tutorial online that explains addEventListener() and the event object clearly.

I created the query variable to make a query string to send to the server. The query string contains all the form data in key-value pairs like this: "firstname=John&lastname=Smith". This is how you send form data in a way that the server can understand it.

The encodeURIComponent() is used to put values into a URL so that the data arrives properly to the server. For example, the "&" symbol is used to separate fields and "=" is used to associate keys with values, so those symbols need to be encoded. This has nothing to do with security, security is handled by PHP.

In Javascript, when a function is defined inside another function it has access to the local variables of that other function, it also can only be used from inside the function that contains it.

Link to comment
Share on other sites

Ok thanks for clarification Ingolme

I used this form to implement it:

<!DOCTYPE html>
		<html>
		<body bgcolor="grey">
		<center>
				<br><br><br>

		 
		<div style="height: 200px; width: 600px; border: solid 2px blue;">

		
		 <form id="my_form" action="" method="post">
		Give your name: <input type="text" name="fname">
		<br>
		 <input type="submit" value="Send" onclick="submitForm(e);"> 
		
		<!--<button type="button" onclick="submitForm(e)">send it</button>-->
		

		</form>

		 
		
		 </div>

 

but the error thrown out is about this piece of code.

      e.preventDefault();

 

the error code says: Reference error is not defined.

e has to be declared. I tried to change fname into e; but that didnt work.

How is this solved?

 

 

 

 

 

Link to comment
Share on other sites

When passing event on calling a function

onclick="submitForm(e)

use 'event' (without quotes) it does not know what a single 'e' refers to, only when it reaches the actual function

function submitForm(e) {

....

....

}

does variable 'e' refer to 'event' to use for

e.preventDefault(); and  e.currentTarget;

 

Link to comment
Share on other sites

 

This is the script right now:

		<!DOCTYPE html>
			<html>
			<head>
				<script>

	// Add a submit event handler to the form
	var form = document.getElementById("my_form");
	form.addEventListener("submit", submitForm, false);  // error

	function submitForm(e) {
	  // Cancel form submission
	  e.preventDefault(); // 

	  // Build a query string from the form data
	  var form = e.currentTarget;
	  var query = "", element;
	  for(var i = 0; i < form.elements.length; i++ ) { // error
		element = form.elements[i];
		if(element.name) {
		  query += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value); 
		  query += "&";
		}
	  }

	  // Send a request
	  var request = new XMLHttpRequest();
	  request.onreadystatechange = doSomething;
	  request.open("POST", "prophp.php", true);
	  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  request.send(query); // Form data is here

	  // Handle response here however you want to
	  function doSomething() {
		if(request.readyState == 4) {
		  if(request.status == 200) {
			// Success
			//
			//
		  } else {
			// Error
			//
			//
		  }
		}
	  }
	  
	  
	}
	</script>
			
	</head>
			
	<body bgcolor="grey">
			<center>
					<br><br><br>

			 
			<div style="height: 200px; width: 600px; border: solid 2px blue;">

			
			 <form id="my_form" action="" method="post">
			Give your name: <input type="text" name="fname">
			<br>
			 <input type="submit" value="Send" onclick="submitForm(event)"> 
			
			<!--<button type="button" onclick="submitForm(e)">send it</button>-->
			

			</form>

			 
			
			 </div>

	</body>

 

The errors are at 2 lines:

form.addEventListener("submit", submitForm, false); 

and

for(var i = 0; i < form.elements.length; i++ ) {

as you see I changed e to event in onclick but no result yet.

 

 

Link to comment
Share on other sites

Lets start with form submission, assigning a onclick to submit button is impractical because a submission can occur if the user presses a enter button on keyboard while within a input, that is why you should use ONSUBMIT on the FORM element, because onsubmit of the FORM element will pick up ANY submission that takes place within it, either by user clicking 'enter' button on keyboard OR user clicking submit button.

NOW!that said, you have two kinds of submission here

(1) what will know be onsubmit on the form element.

(2) the addEventListener which does the same thing

NOW depending on which one you decide to use! determines how you go about adjusting how the function to work to accept a specific version.

 

IF you use (1), you MUST apply onsubmit="submitForm(event)" to the FORM element and the function will be

function submitForm(e)

 

IF you use this (2), the 'event' (without quotes) will be placed in the function as

function submitForm(event)

but you must apply the 'event' argument to 'e' variable

e=event;

to get 

e.preventDefault(); and e.currentTarget

to work;
 

Also currently because var form = document.getElementById("my_form"); AND the addEventListener is placed ABOVE the targeted id element even before it has been rendered, it won't work, and throw an error.

 

Edited by dsonesuk
I felt like it, whats it to do with you?
Link to comment
Share on other sites

I decided to go for routine 1and luckily the errors are gone, but the script does not give a result yet.

I commented the addeventlistener line and the placed onSubmit in the form tag.

			<!DOCTYPE html>
				<html>
				
				
				<body bgcolor="grey">
				<center>
						<br><br><br>

				 
				<div style="height: 200px; width: 600px; border: solid 2px blue;">

				
				 <form id="my_form" action="" method="post" onsubmit="submitForm(event)">
				Give your name: <input type="text" name="fname">
				<br>
				 <input type="submit" value="Send" > 
				
				<!--<button type="button" onclick="submitForm(e)">send it</button>-->
				

				</form>

				 
				
				 </div>

		</body>
				
				
				
					<script>

		// Add a submit event handler to the form
		var form = document.getElementById("my_form");
	//	form.addEventListener("submit", submitForm, false);  // error

		function submitForm(e) {
		  // Cancel form submission
		  e.preventDefault(); // 

		  // Build a query string from the form data
		  var form = e.currentTarget;
		  var query = "", element;
		  for(var i = 0; i < form.elements.length; i++ ) { // error
			element = form.elements[i];
			if(element.name) {
			  query += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value); 
			  query += "&";
			}
		  }

		  // Send a request
		  var request = new XMLHttpRequest();
		  request.onreadystatechange = doSomething;
		  request.open("POST", "prophp.php", true);
		  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		  request.send(query); // Form data is here

		  // Handle response here however you want to
		  function doSomething() {
			if(request.readyState == 4) {
			  if(request.status == 200) {
				// Success
				//
				//
			  } else {
				// Error
				//
				//
			  }
			}
		  }
		  
		  
		}
		</script>
				

				
		 


	</html>

 

I use a php script to process the form data, both echo as well as the dump is not done; its like this:

<?php 


	echo '<br>test code here : ';

	if (isset($_POST['fname']))
	{
		
		var_dump($_POST['fname']);
		
		// execute mysql queries
	}

	?>

 

Quote

Also currently because var form = document.getElementById("my_form"); AND the addEventListener is placed ABOVE the targeted id element even before it has been rendered, it won't work, and throw an error.

 

I don not understand completely what is meant with what the target id element is (is that form?) , I put the form part above the javascript-part.

What I would actually want is an extra div or p element to show the result.

 

 

Link to comment
Share on other sites

The html and JavaScript when loaded is processed from top to bottom of the page, unless you have js code to run after the page is fully loaded, (with you original script with code in between <head>...</head>) it will come to

    var form = document.getElementById("my_form");
    form.addEventListener("submit", submitForm, false);

first, but! it has not yet got to and rendered the form element with 'my_form' id ref

<form id="my_form" action="" method="post" onsubmit="submitForm(event)">

so it does not exist yet! and so throw an undefined error, which means the second won't be initiated either, so no event is assigned to form because of undefined error.

You WON'T see anything yet! because you have not done anything to process the return response if sucessful.

by adding a simple alert you can see what is returned

 if (request.status == 200) {
// Success
                            alert(request.responseText)
//
                        } else {
// Error
//
//
                            alert('not processed')
                        }

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...