Sitemap / Advertise

Information



Tags



Share

How to get response messages from a PHP page via AJAX

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to elicit information from a PHP page as response messages without refreshing via AJAX call in JavaScript. In this way, you can get data from a MySQL database using JavaScript even though you use a LAMP (PHP) server.

The use of jQuery is due to the fact that its features are simple to utilize and implement for this tutorial but you can use plain JavaScript instead.

Click here to inspect all jQuery AJAX Methods.

Code

In JavaScript:

Do not forget to add the jQuery library, as shown below, before executing the given code.

Detect whether the submit button is clicked or not.

Get the query value.

If the query is not null, make an AJAX call (GET)

Show the response message without refreshing the page after success.

In PHP:

If the query variable is set, print the response message, depending on the requested query value, using the Switch/Case statement.


------------------- JavaScript --------------------

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

$("#submit").on("click", () => {
	let query = document.getElementById("query").value;
	if(query != ""){
		$.ajax({
			url: "response.php?query=" + query,
			type: "GET",
			async: true,
			success: (response) => {
				$("#response").html(response);
			}
		});
	}else{
		$("#response").text("Enter a query...");
	}
});

------------------- PHP --------------------

if(isset($_GET['query'])){
	switch($_GET['query']){
		case "How are you?":
		echo "Fine :)";
		break;
		case "Name":
		echo "TheAmplituhedron";
		break;
		case "About":
		echo '<a href="/about" style="color:#002699;">Click here.</a>';
		break;
		case "Projects":
		echo '<a href="/projects" style="color:#002699;">Click here.</a>';
		break;
		case "Tutorials":
		echo '<a href="/articles" style="color:#002699;">Click here.</a>';
		break;
		default:
		echo "Not Detected! Please enter an existing query.";
	}
}

Result:

Waiting...

References

(*) https://www.w3schools.com/jquery/jquery_ref_ajax.asp