Material Box

Material Box

WEB Design & Material Images

JavaScript - Access PHP file using fetch() and then()

JavaScript

A method and simple code example to access a PHP file and get the return value using fetch().then() in JavaScript.


The HTML has a submit button.

<button type="button" id="post-btn">POST Button</button>

The click event of the submit button is implemented with addEventListener().

The send data is created with new FormData(), and sent to the PHP file using fetch() and then().

The code example accesses index.php of the site, gets the page contents as the return value, and logs it to the console.

// Event when button clicked
document.querySelector('#post-btn').addEventListener("click", function () {

	// Create POST data
	const formData = new FormData();
	formData.append('parameter1', 'data1');
	formData.append('parameter2', 'data2');

	// Access PHP file
	fetch('/index.php', {
		method: 'POST',
		body: formData
	})
		.then(response => {
			if (response.ok) {
				return response.text();
			}
			throw new Error('No response');
		})
		.then(data => {
			// Get return value
			console.log(data);
		})
		.catch(error => {
			console.error(error);
		});
		
});

JavaScript - Access PHP file using fetch() and then()

TitleJavaScript - Access PHP file using fetch() and then()

CategoryJavaScript

Created

Update

AuthorYousuke.U