Testing AJAX?

Can you please give us all details of the JavaScript code that deals with xhr, thanks.

sure

<script>
document.getElementById('type').addEventListener('submit', insertType);
function insertType(e) {
	e.preventDefault();
	var type = document.getElementById('type_to_add').value;
	var xhr = new XMLHttpRequest();
	xhr.open("POST","insert_type.php", true);
	
	xhr.onload = function() {
		console.log('Submitted:'+type);
	}
	
	xhr.send();
}
	
	
</script>

idx != id …

Excellent - that code demonstrates why the type information is not being posted.

Here is an example of making a POST request.

Your code doesn’t send anything when it makes your POST request, which is the cause of the problem.

1 Like

I dont understand what this is

xhr.send("foo=bar&lorem=ipsum");

is foo a variable like lorem?

Those are two key/value pairs being sent, where foo is the key and bar is its value, and lorem is another key with ipsum being its value.

oh…I see.
So, in that case 2 variables are being sent and can be used in the other page like

$_POST['foo'];
$_POST['lorem'];
1 Like

I am confused on getting atthe variables from the php page
As you can see, when I submit the form, the variable is captures (Request Payload)


but heres the response

Why does it see the form is submitted, but not the variables?

echo "form submitted";
if(isset($_POST['Type'])) {

	echo $_POST['Type'];
	
	$stmt = $mysqli->prepare("INSERT INTO furniture_types (name) VALUES (?)");
	$stmt->bind_param("s", $_POST['Type']);
	$stmt->execute();
	echo $stmt->error();
/* 		if(!$stmt->error()) {
			echo "inserted";
		} else {
			echo "not inserted";
		} 
*/
	$stmt->close();	  
}

What are you expecting to see there?

i thought id see
form submittedtest type

and i thought the insert query would work

What is it in the PHP code makes you think that you would see “test type”?

This now has nothing to do with JavaScript. The webpage is confirmed to be successfully submitting your desired values as a POST request. Anything else is to do with PHP, so I direct you to the PHP Forum instead.

You sure about that?

Might want to look at those headers again…coughtext/plaincough

How does that cause a problem?

What do you recommend to do about them.

Well you gave a link to the MDN page with the example for a POST.

In that page, it very specifically gives the content type.

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
1 Like

oh, I see
so now that I sent the header it can see the variables
but why is the variable undefined?

Well, read your error.

Where do you define $mysqli ?

perfect, if I include the connection srting it there, it works, thanks

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