AJAX problem with sending a variable list to PHP

Okay must be doing something obviously wrong but can’t pick it.

Am calling js from a submit button on a form, loading a variable list, then calling a php script. The php script is issuing a “Undefined index: first_name” error.

JS code

function ajax_post() {
			// Create our XMLHttpRequest object
			var hr = new XMLHttpRequest();
			// Create some variables we need to send to our PHP file
			var url = "process.php";
			
			var fn = document.getElementById("fname").value;
			var ln = document.getElementById("lname").value;
			var email = document.getElementById("email").value;
			var country = document.getElementById("country").value;
			var un = document.getElementById("uname").value;
			var password = document.getElementById("pass1").value;
			var mreg = "register";
			
			var vars = "opt="+mreg+"&first_name="+fn+"&last_name="+ln+"&email="+email+"&country="+country+"&user_name="+un+"&password="+password;
			alert(vars);
			hr.open("POST", url, true);
			
			// Set content type header information for sending url encoded variables in the request
			hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			
			// Access the onreadystatechange event for the XMLHttpRequest object
			hr.onreadystatechange = function() {
				if(hr.readyState == 4 && hr.status == 200) {
					var return_data = hr.responseText;
					document.getElementById("status").innerHTML = return_data;
				}
			}
			
			// Send the data to PHP now ... and wait for respones to update the status div
			hr.send(vars);
			document.getElementById("status").innerHTML = "processing...";
		}

indent preformatted text by 4 spaces

The alert would seem to show the correct format of the vars string.

PHP

<?php
    $first_name = $_POST['first_name'];
?>

Anyone note what I am doing wrong?

Nothing is immediately obvious to me, but I haven’t used raw XMLHttpRequest for a while, if you polyfil fetch and FormData you can write code like this instead.

fetch('process.php', {
  method: 'POST',
  body: new FormData(document.getElementById('my-form'))
});

If you inspect the request in the browser does it include the post data?

Thanks for the quick reply Mark :slight_smile:

Managed to track down the issue, this is a project being done by four people, the form being developed as an insert file, naturally had form tags around it with a method=“post” and action etc, removal of form tags fixes the issue as the $_POST processing was being called by the form action and not the submit button onClick action variables. If that makes any sort of sense.

Hopefully this helps a few other people.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.